0% found this document useful (0 votes)
3 views56 pages

Khushi Python Final Report

This document is a training report submitted by Khushi Parashar for the Bachelor of Technology degree in Computer Science Engineering, focusing on Python programming. It includes sections on Python's syntax, data types, modules, and practical applications, alongside acknowledgments and a certificate of completion. The report emphasizes Python's versatility and its role in modern software development, supported by various projects and examples.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views56 pages

Khushi Python Final Report

This document is a training report submitted by Khushi Parashar for the Bachelor of Technology degree in Computer Science Engineering, focusing on Python programming. It includes sections on Python's syntax, data types, modules, and practical applications, alongside acknowledgments and a certificate of completion. The report emphasizes Python's versatility and its role in modern software development, supported by various projects and examples.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 56

PYTHON

Training Report

submitted

in partial fulfillment

for the award of the Degree of

Bachelor of Technology

in

Department of Computer Science Engineering

(With Specialization In Computer Science & Engineering)

Supervisor: Submitted By:

Mrs. Dimple Baberwal Khushi Parashar

Assistant Professor RollNo.22EMICS035

Department of Computer Science & Engineering


Modi Institute of Technology
Rajasthan Technical University
September 2025-2026
CANDIDATE’S DECLARATION

I hereby declare that the work, which is being presented in the Training Report, entitled “Python
Programming” in partial fulfillment for the award of Degree of “Bachelor of Technology” in
Department of Computer Engineering with specialization in Computer Science and
Engineering, and submitted to the Department of Computer Science & Engineering, Modi
Institute of Technology, Rajasthan Technical University is a record of my own investigations
carried under the Guidance of Assistant professor, Amrata Pupneja, Dept. of Computer Science
& Engineering.
I have not submitted the matter presented in this Training Report anywhere for the award of any
other Degree.

Khushi Parashar
Computer Science and Engineering
Roll No.: 22EMICS035
Modi Institute of Technology, Kota

Counter Signed By:


Supervisor:
Mrs. Dimple Baberwal
Assistant Professor, CSE Dept.

i
ACKNOWLEDGEMENT

I would also like to give my special thanks to the Principal, Dr. Vikas Soni, Modi Institute of
Technology, for providing the opportunity to me to undertake this work.
I would like to thank my guide Assistant Professor, Mrs. Dimple Baberwal, for their valuable
guidance. I appreciate their presence for all the discussions, suggestions and their time whenever
I needed them.
Two Persons who deserves a First and Foremost mention are my Mother Mrs. Soniya Parashar
and My Father Mr. Narendra Parashar, whose strong belief in my abilities and moral support
uplifted my spirits. Without their encouragement, I would have never imagined to achieve this
height in my career.
I cannot forget to mention the name of my best friends for her relentless help and motivation all
through.
Finally, I would like to thank everybody who was important to the successful realization of this
report, as well as expressing my apology that I could not mention them personally one by one.

Khushi Parashar
Computer Science and Engineering
ROLL No.: 22EMICS035
Modi Institute of Technology, Kota

ii
CERTIFICATE

This is to certify that this Training Report entitled “Python” has been successfully carried out
by Khushi Parashar (Enrolment No.: 22EMICS035), under my supervision and guidance, in
partial fulfillment of the requirement for the award of Bachelor of Technology Degree in
Computer Science & Engineering from Modi Institute of Technology, Kota.

Supervisor:
Mrs. Dimple Baberwal
Assistant Professor, CSE Dept

Place: Kota
Date:

iii
iv
TABLE OF CONTENTS

TITLE PAGE NO.


ABSTRACT 1
Chapter 1 Introduction to Python Programming 2
Chapter 2 Modules, Comments & Pip 3
2.1 Modules
2.2 Pip
2.3 Types of Modules
2.4 Using python as a calculator . 4
2.5 Comments
2.6 Types of Comments
Chapter 3 Variables and Datatype 5
3.1 Data Types
3.2 Rules for choosing an identifier
3.3 Operators in Python
3.4 Type() function and typecasting 6
3.5 Input() Function
Chapter 4 Strings 7
4.1 String Slicing
4.2 Slicing With Skip Value
4.3 String Functions 8
4.4 Escape Sequence Characters 9
Chapter 5 Lists And Tuples 10
5.1 List Indexing
5.2 List methods
5.3 Tuples in Python
5.4 Tuple Methods 11
Chapter 6 Dictionary & Sets 12
6.1 Properties of Python Dictionaries
6.2 Dictionary Methods
6.3 Sets in Python 13
6.4 Properties of Sets

v
6.5 Operations on sets
Chapter 7 Conditional Expression 14
7.1 If Else and Elif in Python
7.2 Relational Operators
7.3 Logical Operators 15
7.4 Elif clause
7.5 Important notes:
Chapter 8 Loops in Python 16
8.1 Types of Loops in Python
8.2 While loop
8.3 For loop
8.4 Range() Function in Python 17
8.4.1 An Example Demonstrating range() function
8.5 For Loop with Else
8.6 The Break Statement
8.7 The Continue Statement 18
8.8 Pass statement
Chapter 9 Functions & Recursions 19
9.1 Example and syntax of a function
9.2 Function call
9.3 Function Definition
9.4 Types of Functions in Python
9.5 Functions with Arguments
9.6 Default Parameter Value 20
9.7 Recursion 21
Project 1 Snake, Water, Gun Game 22
Chapter 10 File I/O 25
10.1 Type of Files
10.2 Opening a File
10.3 Reading a File in Python
10.4 Other methods to read the file 26
10.5 Modes of opening a file
10.6 Write Files in Python
10.7 With Statement .
Chapter 11 Object Oriented Programming 27
11.1 Class
11.2 Object

vi
11.3 Modelling a problem in OOPs
11.4 Class Attributes 28
11.5 Instance attributes
11.6 Self parameter

vii
11.7 Static method 29
11.8 Init() constructor
Chapter 12 Inheritance & more on OOPs 30
12.1 Types of Inheritance
12.1.1 Single Inheritance 31
12.1.2 Multiple Inheritance
12.1.3 Multilevel Inheritance
12.2 Super() method
12.3 Class method
12.4 @property Decorators 32
12.4.1 @getters and @setters
12.5 Operator Overloading in Python

Mega Project 1 Tiny URL 33


Mega Project 2 Caeser Cipher 35
Mega Project 3 Pandemic Simulator 37-43

CONCLUSION 44

FUTURE SCOPE 45
REFERENCE

vii
i
ABSTRACT
Python is a versatile and widely adopted programming language known for its simplicity,
readability, and broad applicability across diverse fields. This report explores the foundational
aspects of Python, including its syntax, key programming paradigms, and comprehensive
standard library, which collectively make it an ideal choice for beginners and professionals alike.
Python’s dynamic nature and emphasis on code clarity have contributed to its popularity for rapid
development and prototyping. The report also addresses Python’s ecosystem, including its
integration with third-party tools, the role of open-source contributions, and its thriving
community that provides extensive documentation and support. Practical examples and case
studies are used to demonstrate Python's capability in solving real-world problems.
The report concludes by highlighting the language's future prospects, its role in the ongoing
evolution of technology, and its contribution to the democratization of programming for users
with diverse levels of expertise. The findings underscore Python's position as a cornerstone of
modern software development.

1
CHAPTER 1
INTRODUCTION TO PYTHON

Python is a versatile and user-friendly programming language. Python's simplicity and


readability make it an ideal starting point for anyone interested in programming. It is known for
its simplicity and readability, making it perfect for beginners. It is a high-level, interpreted
language with a broad range of libraries and frameworks, supporting applications in web
development, data analysis, AI, and more. Python's versatility and ease of use make it a valuable
tool for both novice and experienced programmers. Its clean syntax and English-like structure
make it accessible to both beginners and experienced programmers. With a vast community and
extensive standard library, Python offers a rich ecosystem of tools and resources, making it a
popular choice for developers worldwide.

DEFINITION: Python, is refers to a block of code that declares a function, a class, or another
structure. Python provides the def keyword for defining functions and the class keyword for
defining classes.

The extensive Python Standard Library provides a wide range of modules for common tasks,
reducing the need for writing custom code. Beyond its core features, Python's ecosystem is rich
with third-party libraries and frameworks that cater to specific needs. For web development,
Django and Flask are popular choices, while data analysis and machine learning can be
facilitated by libraries like NumPy, Pandas, and TensorFlow. Python's flexibility and adaptability
have solidified its position as a leading programming language in the modern tech landscape.
Some key aspects of Python's syntax are indentation, comments, variables, data types, operators,
control flow, functions, modules, etc.

2
CHAPTER 2
MODULES, COMMENTS & PIP

Let’s write our very first python program. Create a file called hello.py and paste the below code
in it.
print("hello world") # print is a function (more later)
Execute this file (.py file) by typing python hello.py and you will see Hello World printed on the
screen.
2.1 MODULES
A module is a file containing code written by somebody else (usually) which can be imported
and used in our programs.
2.2 PIP
Pip is the package manager for python. You can use pip to install a module on your
system. pip install flask # Installs Flask Module
2.3 TYPES OF MODULES
There are two types of modules in Python.
1. Built in Modules (Preinstalled in Python)
2. External Modules (Need to install using pip)

Some examples of built in modules are os, random etc.


Some examples of external modules are tensorflow, flask etc.
2.4 USING PYTHON AS A CALCULATOR
We can use python as a calculator by typing “python” + ↵ on the
terminal. This opens REPL or Read Evaluate Print Loop.
2.5 COMMENTS
Comments are used to write something which the programmer does not want to execute. This can
be used to mark author name, date etc.
2.6 TYPES OF COMMENTS
There are two types of comments in python.
1. Single Line Comments: To write a single line comment just add a ‘#’ at the start of the
line. # This is a Single-Line Comment
3
2. Multiline Comments: To write multi-line comments you can use ‘#’ at each line or you can
use the multiline string (""" """)
"""This is an amazing example
of a Multiline
comment!"""

4
CHAPTER 3

VARIABLES AND DATATYPE

A variable is the name given to a memory location in a program. For example.


a= 30 # variables = container to store a value.
b= "harry" # keywords = reserved words in python
c= 71.22 # identifiers = class/function/variable name
3.1 DATA TYPES
Primarily these are the following data types in Python:
1. Integers
2. Floating point numbers
3. Strings
4. Booleans
5. None

Python is a fantastic language that automatically identifies the type of data for us.
a= 71 # identifies a as class <int>
b=88.44 # identifies b as class <float>
name= "harry" # identifies name as class <str>
3.2 RULES FOR CHOOSING AN IDENTIFIER
• A variable name can contain alphabets, digits, and underscores.
• A variable name can only start with an alphabet and underscores.
• A variable name can’t start with a digit.
• No while space is allowed to be used inside a variable name.

Examples of a few variable names are: harry, one8, seven, _seven etc.
3.3 OPERATORS IN PYTHON
Following are some common operators in python:
1. Arithmetic operators: +, -, *, / etc.
2. Assignment operators: =, +=, -= etc.
3. Comparison operators: ==, >, >=, <, != etc.
4. Logical operators: and, or, not.

5
3.4 TYPE() FUNCTION AND TYPECASTING
type() function is used to find the data type of a given variable in python. a = 31
type(a) # class <int> b =
"31"
type (b) # class <str>
A number can be converted into a string and vice versa (if possible) There
are many functions to convert one data type into another. str(31)
=>"31" # integer to string conversion
int("32") => 32 # string to integer conversion float(32) =>
32.0 # integer to float conversion
… and so, on
Here "31" is a string literal and 31 a numeric literal.
3.5 INPUT () FUNCTION
This function allows the user to take input from the keyboard as a string. A =
input ("enter name") # if a is "harry", the user entered harry
It is important to note that the output of input is always a string (even is a number is entered).

6
CHAPTER 4
STRINGS

4.1 Definition
String is a data type in python.
String is a sequence of characters enclosed in quotes.
We can primarily write a string in these three ways.
a ='harry' # Single quoted string
b = "harry" # Double quoted string
c = '''harry''' # Triple quoted string
4.2 STRING SLICING
A string in python can be sliced for getting a part of the strings.
Consider the following string:

Figure 4.1
The index in a sting starts from 0 to (length -1) in Python. In order to slice a string, we use the
following syntax:

Figure 4.2

4.2.1 Negative Indices: Negative indices can also be used as shown in the figure above. -1
corresponds to the (length - 1) index, -2 to (length - 2).
4.3 SLICING WITH SKIP VALUE
We can provide a skip value as a part of our slice like this:
word = "amazing"
word[1: 6: 2] # "mzn"
7
Other advanced slicing techniques:
Word = "amazing"
Word = [:7] # word [0:7] – 'amazing'
Word = [0:] # word [0:7] – 'amazing'
4.4 STRING FUNCTIONS
Some of the commonly used functions to perform operations on or manipulate strings are as
follows. Let us assume there is a string ‘str’ as follows:
str = 'harry'
Now when operated on this string ‘str’, these functions do the following:
1. len () function – This function returns the length of the strings.

str = "harry"
print(len(str)) # Output: 5
2. String.endswith("rry") – This function_ tells whether the variable string ends with the string
"rry" or not. If string is "harry", it returns true for "rry" since Harry ends with rry.

str = "harry"
print(str.endswith("rry")) # Output: True
3. string.count("c") – counts the total number of occurrences of any character.

str = "harry"
count = str.count("r")
print(count) # Output: 2
4. the first character of a given string.

str = "harry"
capitalized_string = str.capitalize()
print(capitalized_string) # Output: "Harry"
1. string.find(word) – This function friends a word and returns the index of first occurrence of that
word in the string.

8
str = "harry"
index = str.find("rr") print(index) #
Output: 2
1. string.replace (old word, new word ) – This function replace the old word with new word in the
entire string.

str = "harry"
replaced_string = str.replace("r", "l") print(replaced_string)
# Output: "hally"
4.5 ESCAPE SEQUENCE CHARACTERS
Sequence of characters after backslash "\" → Escape Sequence characters
Escape Sequence characters comprise of more than one character but represent one character when used
within the strings.
EXAMPLE: \n, \t, \’, \\ etc.
Newline
Tab Backslash
Single quote

9
CHAPTER 5
LISTS AND TUPLES

Python lists are containers to store a set of values of any data type.

Figure 5.1

5.1 LIST INDEXING


A list can be indexed just like a string.
l1 = [7,9,"harry"]
l1[0] # 7
l1[1] # 9
l1[70] # error
l1[0:2] # [7,9] #list slicing
5.2 LIST METHODS
Consider the following list:
l1 = [1,8,7,2,21,15]
• l1.sort(): updates the list to [1,2,7,8,15,21]
• l1.reverse(): updates the list to [15,21,2,7,8,1]
• l1.append(8): adds 8 at the end of the list
• l1.insert(3,8): This will add 8 at 3 index
• l1.pop(2): Will delete element at index 2 and return its value.
• l1.remove(21): Will remove 21 from the list.

5.3 TUPLES IN PYTHON


A tuple is an immutable data type in python.
a = () # empty tuple
a = (1,) # tuple with only one element needs a comma
a = (1,7,2) # tuple with more than one element
10
5.4 TUPLE METHODS
Consider the following tuple.
a = (1, 7, 2)
• a.count (1): a count (1) will return number of times 1 occurs in a.
• a.index (1) will return the index of first occurrence of 1 in a.

11
CHAPTER 6
DICTIONARY & SETS

Dictionary is a collection of keys-value pairs.


Syntax:
a={
"key": "value",
"harry": "code",
"marks": "100",
"list": [1, 2, 9]
}
print(a["key"]) # Output: "value"
print(a["list"]) # Output: [1, 2, 9]
6.1 PROPERTIES OF PYTHON DICTIONARIES
1. It is unordered.
2. It is mutable.
3. It is indexed.
4. Cannot contain duplicate keys.

6.2 DICTIONARY METHODS


Consider the following dictionary.
a={"name":"harry"
"from":"india" "marks":[92,98,96]}
• a.items(): Returns a list of (key,value)tuples.
• a.keys(): Returns a list containing dictionary's keys.
• a.update({"friends":}): Updates the dictionary with supplied key-value pairs.
• a.get("name"): Returns the value of the specified keys (and value is returned
eg."harry" is returned here).
• More methods are available on docs.python.org

12
6.3 SETS IN PYTHON
Set is a collection of non-repetitive elements. s =
set() # no repetition allowed!
s.add(1)
s.add(2) # or set ={1,2}
If you are a programming beginner without much knowledge of mathematical operations on sets, you
can simply look at sets in python as data types containing unique values.
6.4 PROPERTIES OF SETS
1. Sets are unordered => Element’s order doesn’t matter
2. Sets are unindexed => Cannot access elements by index
3. There is no way to change items in sets.
4. Sets cannot contain duplicate values.

6.5 OPERATIONS ON SETS


Consider the following set:
s = {1,8,2,3}
• len(s): Returns 4, the length of the set
• s.remove(8): Updates the set s and removes 8 from s.
• s.pop(): Removes an arbitrary element from the set and return the element removed.
• s.clear():empties the set s.
• s.union({8,11}): Returns a new set with all items from both sets. {1,8,2,3,11}.
• s.intersection({8,11}): Return a set which contains only item in both sets {8}.

Figure 6.1

13
CHAPTER 7
CONDITIONAL EXPRESSION

Sometimes we want to play PUBG on our phone if the day is Sunday.


Sometimes we order Ice Cream online if the day is sunny.
Sometimes we go hiking if our parents allow.
All these are decisions which depend on a condition being met.
In python programming too, we must be able to execute instructions on a condition(s) being met.
This is what conditionals are for!
7.1 IF ELSE AND ELIF IN PYTHON
If else and elif statements are a multiway decision taken by our program due to certain conditions
in our code.
Syntax:
if (condition1): # if condition1 is True
print ("yes")
elif(condition2): # if condition2 is True
print("no")
else: # otherwise
print("maybe")
CODE EXAMPLE.
a=22
if(a>9):
print("greater")
else:
print("lesser")
7.2 RELATIONAL OPERATORS
Relational Operators are used to evaluate conditions inside the if statements. Some examples of
relational operators are:
==: equals.
> =: greater than/ equal to.
< =: lesser than/ equal to.

14
7.3 LOGICAL OPERATORS
In python logical operators operate on conditional statements. For Example:
• and – true if both operands are true else false.
• or – true if at least one operand is true or else false.
• not – inverts true to false & false to true.

7.4 ELIF CLAUSE


elif in python means [else if]. An if statements can be chained together with a lot of these elif
statements followed by an else statement.
if (condition1):
#code
elif (condition2): # this ladder will stop once a condition in an if or
elif is met.
#code
elif(condition3):
#code
else:
#code
7.5 IMPORTANT NOTES:
1. There can be any number of elif statements.
2. Last else is executed only if all the conditions inside elifs fail.

15
CHAPTER 8
LOOPS IN PYTHON

Sometimes we want to repeat a set of statements in our program. For instance: Print 1 to 1000. Loops
make it easy for a programmer to tell the computer which set of instructions to repeat and how!
8.1 TYPES OF LOOPS IN PYTHON
Primarily there are two types of loops in python.
• while loops
• for loops
We will look into these one by one.
8.2 WHILE LOOP
Syntax:
while (condition): # The block keeps executing until the condition is true #Body
of the loop
In while loops, the condition is checked first. If it evaluates to true, the body of the loop is executed
otherwise not!
If the loop is entered, the process of [condition check & execution] is continued until the condition
becomes False.
Example:
i=0
while i < 5: # print "Harry" – 5 times!
print("Harry")
i=i+1
Note: If the condition never become false, the loop keeps getting executed.
8.3 FOR LOOP
A for loop is used to iterate through a sequence like list, tuple, or string [iterables]
Syntax:
l = [1, 7, 8]
for item in l:
print(item) # prints 1, 7 and 8

16
8.4 RANGE FUNCTION IN PYTHON
The range() function in python is used to generate a sequence of number.
We can also specify the start, stop and step-size as follows:
range(start, stop, step_size)
# step_size is usually not used with range()
8.4.1 AN EXAMPLE DEMONSTRATING RANGE () FUNCTION
for i in range(0,7): # range(7) can also be used.
print(i) # prints 0 to 6
8.5 FOR LOOP WITH ELSE
An optional else can be used with a for loop if the code is to be executed when the loops
exhausts.
Example:
l= [1,7,8]
for item in l:
print(item)
else:
print("done") # this is printed when the loop exhausts!
Output:
1
7
8
done
8.6 THE BREAK STATEMENT
‘break’ is used to come out of the loop when encountered. It instructs the program to – exit the
loop now.
Example:
for i in range (0,80):
print(i) # this will print 0,1,2 and 3
if i==3
print(break)

17
8.7 THE CONTINUE STATEMENT
‘continue’ is used to stop the current iteration of the loop and continue with the next one. It
instructs the Program to “skip this iteration”.
Example:
for i in range(4):
print("printing")
if i == 2: # if i is 2, the iteration is skipped
continue
print(i)
8.8 PASS STATEMENT
Pass is a null statement in python.
It instructs to “do nothing”.
Example:
l = [1,7,8]
for item in l:
pass
# without pass, the program will throw an error

18
CHAPTER 9
FUNCTIONS & RECURSIONS

A function is a group of statements performing a specific task.


When a program gets bigger in size and its complexity grows, it gets difficult for a program to
keep track on which piece of code is doing what!
A function can be reused by the programmer in a given program any number of
9.1 EXAMPLE AND SYNTAX OF A FUNCTION
The syntax of a function looks as follows:
def func1():
print('hello')
This function can be called any number of times, anywhere in the program.
9.2 FUNCTION CALL
Whenever we want to call a function, we put the name of the function followed by parentheses as
follows:
func1() # This is called function call.
9.3 FUNCTION DEFINITION
The part containing the exact set of instructions which are executed during the function call.
9.4 TYPES OF FUNCTIONS IN PYTHON
There are two types of functions in python:
• Built in functions (Already present in python).
• User defined functions (Defined by the user).
Examples of built in functions includes len(), print(), range() etc.
The func1() function we defined is an example of user defined function.
9.5 FUNCTIONS WITH ARGUMENTS
A function can accept some value it can work with. We can put these values in the parentheses.
A function can also return value as shown below:
def greet(name):
gr = "hello"+
name return gr
a = greet ("carry")

19
# a will now contain "hello carry"
9.6 DEFAULT PARAMETER VALUE
We can have a value as default as default argument in a function.
If we specify name = “stranger” in the line containing def, this value is used when no argument is
passed.
Example:
def greet(name = "stranger"):
# function body
greet() # name will be "stranger" in function body (default)
greet("carry") # name will be "harry" in function body (passed)
9.7 RECURSION
Recursion is a function which calls itself.
It is used to directly use a mathematical formula as function.
Example:
factorial(n) = n x factorial (n-1)
This function can be defined as follows:
def factorial(n)
if i== 0 or i==1:
# base condition which doesn’t call the function any further
return 1
else:
return n*factorial(n-1) # function calling itself
This works as follows:

Figure 9.1

20
The programmer needs to be extremely careful while working with recursion to ensure that the
function doesn’t infinitely keep calling itself. Recursion is sometimes the most direct way to code
an algorithm.

21
PROJECT 1
SNAKE, WATER, GUN GAME

Snake Water Gun is one of the famous two-player game played by many people. It is a hand
game in which the player randomly chooses any of the three forms i.e. snake, water, and gun.
Following are the rules of the game:
Snake vs Water: Snake drinks the water hence wins.
Water vs. Gun: The gun will drown in water, hence a point for water
Gun vs. Snake: Gun will kill the snake and win.
In situations where both players choose the same object, the result will be a draw.
We will use random.choice() method and nested if-else statements to select a random item from a
list.
#Source Code
# Import random module
import random
print('Snake - Water - Gun')

# Input no. of rounds


n = int(input('Enter number of rounds: '))

# List containing Snake(s), Water(w),


Gun(g) options = ['s', 'w', 'g']

# Round numbers
rounds = 1

# Count of computer wins


comp_win = 0

# Count of player wins


user_win = 0

# There will be n rounds of game


22
while rounds <= n:

# Display round
print(f"Round :{rounds}\nSnake - 's'\nWater - 'w'\nGun - 'g'")

# Exception handling
try:
player = input("Choose your option: ")
except EOFError as e:
print(e)

# Control of bad inputs


if player != 's' and player != 'w' and player != 'g':
print("Invalid input, try again\n")
continue

# random.choice() will randomly choose


# item from list- options
computer = random.choice(options)

# Conditions based on the game rule


if computer == 's':
if player == 'w':
comp_win += 1
elif player == 'g':
user_win += 1

elif computer == 'w':


if player == 'g':
comp_win += 1
elif player == 's':
user_win += 1

23
elif computer == 'g':
if player == 's':
comp_win += 1
elif player == 'w':
user_win += 1

# Announce winner of every


round if user_win > comp_win:
print ("You Won round {rounds}\
n") elif comp_win > user_win:
print ("Computer Won round {rounds}\n")
else:
print("Draw!\n")

rounds += 1

# Final winner based on the number of wons


if user_win > comp_win:
print ("Congratulations!! You Won")
elif comp_win > user_win:
print ("You
lose!!") else:
print ("Match Draw!!")

24
CHAPTER 10
FILE I/O

The random-access memory is volatile, and all its contents are lost once a program terminates. In
order to persist the data forever, we use files.
A file is data stored in a storage device. A python program can talk to the file by reading content
from it and writing content to it.

Figure 10.1

10.1 TYPE OF FILES


There are 2 types of files:
1. Text files (.txt, .c, etc)
2. Binary files (.jpg, .dat, etc)

Python has a lot of functions for reading, updating, and deleting files.

10.2 OPENING A FILE


Python has an open() function for opening files. It takes 2 parameters: filename and mode.
# open("filename", "mode of opening(read mode by default)")
open("this.txt", "r")
10.3 READING A FILE IN PYTHON
# Open the file in read mode
f = open("this.txt", "r")

25
# Read its contents
text = f.read()
# Print its contents
print(text)
# Close the file
f.close()
10.4 OTHER METHODS TO READ THE FILE
We can also use f.readline() function to read one full line at a time.
f.readline() # Read one line from the file.
10.5 MODES OF OPENING A FILE
r – open for reading
w - open for writing
a - open for appending
+ - open for updating.
‘rb’ will open for read in binary mode.
‘rt’ will open for read in text mode.
10.6 WRITE FILES IN PYTHON
In order to write to a file, we first open it in write or append mode after which, we use the
python’s f.write() method to write to the file!
# Open the file in write mode
f = open("this.txt", "w")
# Write a string to the file
f.write("this is nice")
# Close the file
f.close()
10.7 WITH STATEMENT
The best way to open and close the file automatically is the with statement.
# Open the file in read mode using 'with', which automatically closes the
file with open("this.txt", "r") as f:
# Read the contents of the file
text = f.read()
# Print the contents print(text)
26
CHAPTER 11
OBJECT ORIENTED PROGRAMMING

Solving a problem by creating object is one of the most popular approaches in programming.
This is called object-oriented programming.
This concept focuses on using reusable code (DRY Principle).
11.1 CLASS
A class is a blueprint for creating object.

Figure 11.1

Syntax:
class Employee: # Class name is written in pascal case
# Methods & Variables
11.2 OBJECT
An object is an instantiation of a class. When class is defined, a template (info) is defined.
Memory is allocated only after object instantiation.
Objects of a given class can invoke the methods available to it without revealing the
implementation details to the user. – Abstractions & Encapsulation!
11.3 MODELLING A PROBLEM IN OOPS
We identify the following in our problem.
• Noun → Class → Employee
• Adjective → Attributes → name, age, salary

27
• Verbs → Methods → getSalary(), increment()
11.4 CLASS ATTRIBUTES
An attribute that belongs to the class rather than a particular object.
Example:
class Employee:
company = "Google" # Specific to Each Class carry =
Employee() # Object Instatiation
carry.company
Employee.company = "YouTube" # Changing Class Attribute
11.5 INSTANCE ATTRIBUTES
An attribute that belongs to the Instance (object). Assuming the class from the previous example:
carry.name = "carry"
carry.salary = "30k" # Adding instance attribute
Note: Instance attributes, take preference over class attributes during assignment &
retrieval.
When looking up for carry.attribute it checks for the following:
1) Is attribute present in object?
2) Is attribute present in class?
11.6 SELF PARAMETER
self refers to the instance of the class. It is automatically passed with a function call from an object.
carry.getSalary() # here self is carry
# equivalent to Employee.getSalary(carry) The
function getSalary() is defined as: class
Employee:
company = "Google" def
getSalary(self):
print("Salary is not there")

28
11.7 STATIC METHOD
Sometimes we need a function that does not use the self-parameter. We can define a static
method like this:
@staticmethod # decorator to mark greet as a static method
def greet():
print("Hello user")
11.8 INIT () CONSTRUCTOR
init () is a special method which is first run as soon as the object is created.
init () method is also known as constructor.
It takes ‘self’ argument and can also take further arguments.
For Example:
class Employee:
def init (self, name):
self.name=name
def getSalary(self):
...
carry = Employee("Carry")

29
CHAPTER 12
INHERITANCE & MORE ON OOPS

Inheritance is a way of creating a new class from an existing class.


Syntax:
class Employee: # Base class
# Code
class Programmer(Employee): # Derived or child class
# Code
We can use the method and attributes of ‘Employee’ in ‘Programmer’ object.
Also, we can overwrite or add new attributes and methods in ‘Programmer’ class.
12.1 TYPES OF INHERITANCE
• Single inheritance
• Multiple inheritance
• Multilevel inheritance

12.1.1 SINGLE INHERITANCE


Single inheritance occurs when child class inherits only a single parent class.
Figure 12.1

Base

Derived

30
12.1.2 MULTIPLE INHERITANCE
Multiple Inheritance occurs when the child class inherits from more than one parent classes.

Figure 12.2

12.1.3 MULTILEVEL INHERITANCE


When a child class becomes a parent for another child class.

Figure 12.3
12.2 SUPER () METHOD
super() method is used to access the methods of a super class in the derived class.
super(). init ()
# init () Calls constructor of the base class.
12.3 CLASS METHOD
A class method is a method which is bound to the class and not the object of the class.
@classmethod decorator is used to create a class method.
Syntax:
@classmethod
def(cls,p1,p2):

31
12.4 @PROPERTY DECORATORS
Consider the following class:
class Employee:
@property
def name(self):
return self.ename
If e = Employee() is an object of class employee, we can print (e.name) to print the ename by
internally calling name() function.
12.4.1 @.GETTERS AND @.SETTERS
The method name with ‘@property’ decorator is called getter method.
We can define a function + @ name.setter decorator like below:
@name.setter
def name (self,value):
self.ename = value
12.5 OPERATOR OVERLOADING IN PYTHON
Operators in Python can be overloaded using dunder methods.
These methods are called when a given operator is used on the objects.
Operators in Python can be overloaded using the following methods:
p1+p2 # p1. add (p2)
p1-p2 # p1. sub (p2)
p1*p2 # p1. mul (p2)
p1/p2 # p1. truediv (p2)
p1//p2 # p1. floordiv (p2)
Other dunder/magic methods in Python:
str () # used to set what gets displayed upon calling str(obj)
len () # used to set what gets displayed upon calling. len () or len(obj)

32
MEGA PROJECT 1

TINY URL

import random
import string
d = {}

# Function to generate a short URL


def getShortURL(originalURL):
l = random.randint(5, 10)
print('Randomly generated word length:', l)
chars = string.ascii_lowercase
shortURL = ''.join(random.choice(chars) for i in range(l))
print('Randomly generated word:', shortURL)

if shortURL in d:
return getShortURL(originalURL)
else:
d[shortURL] = originalURL
print('Dictionary is:', d)
r = 'https://www.shortURL.com/' + shortURL
return r
# Function to retrieve the original URL
def originalURL(shortURL):
k = shortURL[25:] # This assumes the base URL is 24 characters long
# print(k)
if k in d:
return d[k]
else:
return 'Original URL not found'

33
# Example usage
short =
getShortURL("https://www.example.com/")
print('Short URL:', short)
original = originalURL(short)
print('Original URL:', original)

#Output 1
Randomly generated word length: 6
Randomly generated word: almdwl
Dictionary is: {'almdwl': 'https://www.example.com/'}
Short URL: https://www.shortURL.com/almdwl
Original URL: https://www.example.com/

print(getShortURL("www.iamlearningpython"))

#Output 2
Randomly generated word length: 8
Randomly generated word: bbivrnni
Dictionary is: {'almdwl': 'https://www.example.com/',
'bbivrnni': 'www.iamlearningpython'}
https://www.shortURL.com/bbivrnni

34
MEGA PROJECT 2

CAESAR CIPHER

## Text Encryption & decryption based on the key provided by the user
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y,
Z
1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26
# Message = hi
# key = 3

# encryption at A's
end #

# h = 8+3 = 11
(k) # i = 9+3 = 12
(l)
# encryptedText = kl ; key = 3

# decryption at B's end


#

# k = 11-3 = 8 (h)
# l = 12-3 = 9 (i)
# decryptedText = hi
#
# message = XYZ ; key = 3
alphabet = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', ' w', 'x', 'y', 'z']

choice = input("Enter your choice 'encrypt' or 'decrypt' \n")


text = input(' Enter your message : \n')
key = int(input("Enter the key : \n"))
# encryption function
35
def encrypt(message , shift):

36
encryptedText = ""
for letter in
message:
pos = alphabet.index(letter)
newPos = (pos + shift) % 26
encryptedText += alphabet[newPos]
print('The encrypted text is : ', encryptedText)
# decryption function
def decrypt(message , shift):
decryptedText = ""
for letter in message:
pos = alphabet.index(letter)
newPos = (pos - shift) % 26
decryptedText += alphabet[newPos]
print('The decrypted text is : ',
decryptedText) if choice == 'encrypt':
encrypt(text , key)
elif choice == 'decrypt':
decrypt(text , key)
else:
print('Enter the correct Choice')

#Output
Enter your choice 'encrypt' or 'decrypt'
decrypt
Enter your message :
qzuipo
Enter the key :
1
The decrypted text is : python

37
MEGA PROJECT 3

PANDEMIC SIMULATOR

import random
class Simulation:
'''A class to control simulation & help facilitate the spread of the disease'''
def init (self):
self.dayNumber = 1
print("To proceed with the simulation we must know the population size")
self.populationSize = int(input("Enter the population size: "))

print("\nEpidemic starts with infecting a portion of the population")


self.infectionPercentage = float(input("Enter the percentage (0-100) of the population to
initially infect: "))
self.infectionPercentage /= 100

self.infectionProbability = float(input("Enter probability (0-100) that a person gets infected


when exposed to a disease: "))
self.infectionProbability /= 100

print("\nTo proceed with the simulation we must know how long the infection will last
when exposed")
self.infectionDuration = int(input("Enter the duration (in days) of the infection: "))

print("\nTo proceed with the simulation we must know the mortality rate of infected
people")
self.mortalityRate = float(input("Enter the mortality rate (0-100) of infected people: "))
self.mortalityRate /= 100

print("\nTo proceed with the simulation we must know how long to run the simulation")
self.simulationDays = int(input("Enter the number of days to simulate: "))

38
class Person:
'''Class to represent an individual in the population'''
def init (self):
self.isInfected = False # Person will not be infected initially
self.isDead = False # Person will not be dead initially
self.daysInfected = 0 # To track the days a person is infected for

def infect(self, simulation):


# Generate a random value that is the probability of an individual to get infected
if random.random() < simulation.infectionProbability:
self.isInfected = True

def heal(self):
self.isInfected = False
self.daysInfected = 0

def die(self):
self.isDead = True

def update(self, simulation):


# Update individual
# Check if person is not dead
if not self.isDead:
# If person is infected
if self.isInfected:
self.daysInfected += 1
# Generate a random number and check with mortality
if random.random() < simulation.mortalityRate:
self.die()
elif self.daysInfected >= simulation.infectionDuration:
self.heal()

39
class Population:
'''To handle the whole population'''
def init (self, simulation):
self.population = [Person() for _ in range(simulation.populationSize)]
def initialInfection(self, simulation):
infectedCount = int(round(simulation.infectionPercentage * simulation.populationSize,0))

# Infect exact number of people


for i in range(infectedCount):
self.population[i].isInfected =
True
self.population[i].daysInfected = 1

random.shuffle(self.population)

def spreadInfection(self, simulation):


# Spread to nearby people
for i in range(len(self.population)):
if not self.population[i].isDead:
# For the 1st person in the list, check the next person
if i == 0:
if self.population[i+1].isInfected:
self.population[i].infect(simulation)

# Person in the middle, check left and right


elif i < len(self.population) - 1:
if self.population[i-1].isInfected or self.population[i+1].isInfected:

self.population[i].infect(simulation)

40
# For the last person in the list, check the previous person
else:
if self.population[i-1].isInfected:
self.population[i].infect(simulation)

def update(self, simulation):


simulation.dayNumber += 1

# Update each person


for person in self.population:
person.update(simulation)

def showStatistics(self, simulation):


totalInfectedCount = sum(1 for person in self.population if person.isInfected)
totalDeathCount = sum(1 for person in self.population if person.isDead)

# Percentage of population infected or dead


infectedPercent = round(100 * (totalInfectedCount / simulation.populationSize), 4)
deathPercent = round(100 * (totalDeathCount / simulation.populationSize), 4)

# Summary
print(f"\nDay Number: {simulation.dayNumber}")
print(f"Percentage of population Infected: {infectedPercent}%")
print(f"Percentage of population dead: {deathPercent}%")
print(f"Total people Infected: {totalInfectedCount}/{simulation.populationSize}")
print(f"Total Deaths: {totalDeathCount}/{simulation.populationSize}")

def graphics(self):
status = []

for person in self.population:


if person.isDead:

41
char = 'X'
else:
char = 'I' if person.isInfected else 'O'
status.append(char)
print('-'.join(status))

# Main code
# Simulation object
sim = Simulation()

# Population object
pop = Population(sim)

# Set the initial infection condition


pop.initialInfection(sim)

# Display statistics
pop.showStatistics(sim)

# Show graphics
pop.graphics()

input("\nPress Enter to begin the simulation")

# Run the simulation


for i in range(1,
sim.simulationDays):
pop.spreadInfection(sim)
pop.update(sim)
pop.showStatistics(sim)
pop.graphics()

if i != sim.simulationDays - 1:
42
input("Press Enter to continue the simulation...")

#Output
To proceed with the simulation we must know the population size
Enter the population size: 250

Epidemic starts with infecting a portion of the population


Enter the percentage (0-100) of the population to initially infect: 12.5
Enter probability (0-100) that a person gets infected when exposed to a disease:
2.2

To proceed with the simulation we must know how long the infection will last
when exposed
Enter the duration (in days) of the infection: 12

To proceed with the simulation we must know the mortality rate of infected
people
Enter the mortality rate (0-100) of infected people: 8.5

To proceed with the simulation we must know how long to run the simulation
Enter the number of days to simulate: 5

Day Number: 1
Percentage of population Infected: 12.4%
Percentage of population dead: 0.0%
Total people Infected: 31/250
Total Deaths: 0/250
I-O-O-O-O-O-O-O-O-O-O-I-O-O-O-O-O-I-O-I-O-O-O-O-I-O-O-I-O-I-O-O-O-O-O-O-O-O-O-
OO-O-I-O-O-O-O-O-I-I-I-O-O-O-O-O-O-O-O-O-O-O-O-I-O-O-O-I-O-O-O-O-O-O-O-O-O-O-
O-IO-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-I-O-O-O-O-O-O-O-O-O-O-
I-O-O-IO-O-O-O-O-I-O-O-O-O-O-O-O-O-O-O-I-I-O-O-O-O-O-O-O-O-O-O-O-O-I-O-O-O-O-

43
O-O-O-O-IO-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-I-O-
O-I-O-O-O-I-OO-O-O-I-O-O-O-I-O-O-O-O-O-I-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-
O-O-O-O-O-O-O-OO-O-I-O-O-I-O-I-O-O
Press Enter to begin the simulation 1

Day Number: 2
Percentage of population Infected: 12.8%
Percentage of population dead: 1.2%
Total people Infected: 32/250
Total Deaths: 3/250
X-O-O-O-O-O-O-O-O-O-O-I-O-O-O-O-O-I-O-I-O-O-O-O-I-O-O-I-O-X-O-O-O-O-O-O-O-O-
O-O-O-O-I-O-O-O-O-O-I-I-I-O-O-O-O-O-O-O-O-O-O-O-O-I-O-O-O-I-O-O-O-O-O-O-O-O-O-
O-O-I-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-I-O-O-O-O-O-O-O-O-
O-I-I-O-O-X-O-O-O-O-O-I-O-O-O-O-O-O-O-O-O-O-I-I-O-O-O-O-O-O-O-O-O-O-O-O-I-O-O-
O-O-O-O-O-O-I-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-
O-I-O-O-I-O-O-O-I-O- O-O-O-I-O-O-O-I-O-O-O-O-O-I-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-
O-O-O-O-O-O-O-O-O-O-O-O-O-I-O-O-I-O-I-O-O

Press Enter to continue the simulation…


Day Number: 3
Percentage of population Infected: 13.6%
Percentage of population dead: 2.4%
Total people Infected: 34/250
Total Deaths: 6/250
X-O-O-O-O-O-O-O-O-O-O-I-O-O-O-O-O-I-O-I-O-O-O-O-I-O-O-I-O-X-O-O-O-O-O-O-O-O-
O-O-O-O-I-O-O-O-O-O-X-I-I-O-O-O-O-O-O-O-O-O-O-O-O-I-O-O-O-X-O-O-O-O-O-O-O-O-
O-O-O-I-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-I-O-O-O-O-O-O-O-
O-O-I-I-O-O-X-O-O-O-O-O-I-O-O-O-O-O-O-O-O-O-O-I-I-I-O-O-O-O-O-O-O-O-O-O-O-X-O-
O-O-O-O-O-O-O-IO-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-O-
O-O-I-O-O-I-O-O-O-I-O-O-O-O-I-O-O-O-I-O-O-O-O-O-I-O-O-O-O-O-O-O-O-O-O-O-O-O-O-
O-O-O-O-O-O-O-O-O-O-O-OO-O-I-I-O-I-O-I-O-O

44
CONCLUSION

I believe the trial has shown conclusively that it is both possible and desirable to use Python
asthe principal teaching language:
• It is Free (as in both cost and source code).

• It is trivial to install on a Windows PC allowing students to take their interest further. For many
the hurdle of installing a Pascal or C compiler on a Windows machine is either too expensive or
too complicated;
• It is a flexible tool that allows both the teaching of traditional procedural programmingand
modern OOP; It can be used to teach a large number of transferable skills.
• It is a real-world programming language that can be and is used in academia and the commercial
world;
• It appears to be quicker to learn and, in combination with its many libraries, this offers the
possibility of more rapid student development allowing the course to be made morechallenging
and varied; and most importantly, its clean syntax offers increasedunderstanding and enjoyment
for students.
• With a vast collection of libraries, Python allows students to explore fields like data science,
machine learning, web development, and more without needing additional programming
languages. This versatility also means students can see practical applications of their skills early
on.
• Python is cross-platform, meaning code written on one operating system (Windows, macOS, or
Linux) can typically run on another with little to no modification. This flexibility allows students
to collaborate and work on various devices, fostering a moreinclusive learning environment.

45
FUTURE SCOPE

The future of Python looks extremely promising due to several factors. Here are a few key areas where
Python is expected to continue making significant strides:
1. Artificial Intelligence and Machine Learning

Python has established itself as the go-to language for AI and ML, thanks to its simplicity andthe
powerful libraries available, such as TensorFlow, Keras, and Scikit-learn. As these fields grow,
Python's role in them will likely expand, driving innovation in technology and various industries.
2. Data Science and Analytics

With the exponential growth of data, the need for efficient data analysis tools is greater than ever.
Python, with libraries like Pandas, NumPy, and Matplotlib, is a favorite among data scientists for
its ability to handle complex data sets and perform data visualization. The demandfor data
scientists proficient in Python will continue to rise.
3. Web Development

Frameworks like Django and Flask have made Python a popular choice for web development.The
simplicity of the language and the robustness of these frameworks ensure that Python remains a
preferred language for building scalable and secure web applications.
4. Automation

Python's ease of use and powerful scripting capabilities make it an excellent choice for automation tasks.
From simple scripts to complex workflows, Python is used to automate repetitive tasks across
various domains, including network automation, testing, and data processing
5. IoT (Internet of Things)

Python's role in IoT is growing as well, with libraries like MicroPython and frameworks that support
hardware interaction.

46
REFERENCE

 http://python.org
 https://stackoverflow.blog/2021/07/14/getting-started-with-python
 https://en.wikipedia.org/wiki/python_(programming_language)
 https://www.geeksforgeeks.org/
 https://www.vgtindia.org/training/training.python

You might also like