Khushi Python Final Report
Khushi Python Final Report
Training Report
submitted
in partial fulfillment
Bachelor of Technology
in
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
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
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
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
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)
4
CHAPTER 3
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
11
CHAPTER 6
DICTIONARY & SETS
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.
Figure 6.1
13
CHAPTER 7
CONDITIONAL EXPRESSION
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.
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
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')
# Round numbers
rounds = 1
# 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)
23
elif computer == 'g':
if player == 's':
comp_win += 1
elif player == 'w':
user_win += 1
rounds += 1
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
Python has a lot of functions for reading, updating, and deleting files.
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
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
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 = {}
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
# 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']
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("\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 heal(self):
self.isInfected = False
self.daysInfected = 0
def die(self):
self.isDead = True
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))
random.shuffle(self.population)
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)
# 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 = []
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)
# Display statistics
pop.showStatistics(sim)
# Show graphics
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
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
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