Project 9
Project 9
Project 9
By
Trainer
Mohammad Majeed
TechIn It processing
Syllabus
Introduction To Python
History of Python Features of Python
Python Syntax
Python Variables
Python Comments
Python Data Types
Python Numbers
Python Casting
Python Strings
Python Booleans
Python Operators
Python List
Python Tuples
Python Dictionaries
Python If… Else
Python While Loops
Python For Loops
Python Functions
Python Lambda
Python Arrays
Python Classes/Objects
Python Inheritance
Python Iterators
Python Polymorphism
Python Scope
Python Modules
Python Dates
Python Math
Python JSON
Python RegEx
Python PIP
Python Try… Except
Python User Input
Python String Formating
File Handling
Python File Handling
Python Read Files Python
2
Introduction to Python and installation:
Python is a widely used general-purpose, high level programming language. It was initially designed by Guido van
Rossum in 1991 and developed by Python Software Foundation. It was mainly developed for emphasis on code
readability, and its syntax allows programmers to express concepts in fewer lines of code.
Python is a programming language that lets you work quickly and integrate systems more efficiently.
There are two major Python versions- Python 2 and Python 3.
On 16 October 2000, Python 2.0 was released with many new features.
On 3rd December 2008, Python 3.0 was released with more testing and includes new features.
Installation:
There are many interpreters available freely to run Python scripts like IDLE (Integrated Development
Environment) which is installed when you install the python software from http://python.org/downloads/
Steps to be followed and remembered:
Step 1: Select Version of Python to Install. Step 2: Download Python Executable Installer. Step 3: Run Executable
Installer.
Step 4: Verify Python Was Installed On Windows.
4
Step 5: Verify Pip Was Installed.
Step 6: Add Python Path to Environment Variables (Optional)
PVM
m.py m.pyc
5
Running Python in interactive mode:
Without passing python script file to the interpreter, directly execute code to Python prompt. Once you’re inside
the python interpreter, then you can start.
>>> print("hello world") hello world
# Relevant output is displayed on subsequent lines without the >>> symbol
>>> x=[0,1,2]
# Quantities stored in memory are not displayed by default.
>>> x
#If a quantity is stored in memory, typing its name will display it. [0, 1, 2]
>>> 2+3
5
The chevron at the beginning of the 1st line, i.e., the symbol >>> is a prompt the python interpreter uses to indicate
that it is ready. If the programmer types 2+6, the interpreter replies 8.
Data types:
The data stored in memory can be of many types. For example, a student roll number is stored as a numeric value
and his or her address is stored as alphanumeric characters. Python has various standard data types that are used to
define the operations possible on them and the storage method for each of them.
Int:
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
>>> print(24656354687654+2) 24656354687656
>>> a=10
>>> print(a) 10
# To verify the type of any object in Python, use the type() function:
>>> type(10)
<class 'int'>
>>> a=11
>>> print(type(a))
<class 'int'>
Float:
Float, or "floating point number" is a number, positive or negative, containing one or more decimals.
Float can also be scientific numbers with an "e" to indicate the power of 10.
>>> y=2.8
>>> y 2.8
>>> y=2.8
>>> print(type(y))
<class 'float'>
6
>>> type(.4)
<class 'float'>
>>> 2.
2.0
Boolean:
Objects of Boolean type may have one of two values, True or False:
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
String:
1. Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python
allows for either pairs of single or double quotes.
'hello' is the same as "hello".
Strings can be output to screen using the print function. For example: print("hello").
>>> print("TECHIN IT college") TECHIN IT college
>>> type("TECHIN IT college")
<class 'str'>
7
>>> print('TECHIN IT college') TECHIN IT college
>>> " "
''
In Python (and almost all other common computer languages), a tab character can be specified by the escape
sequence \t:
>>> print("a\tb") a b
List:
It is a general purpose most widely used in data structures
List is a collection which is ordered and changeable and allows duplicate members. (Grow and shrink as
needed, sequence type, sortable).
To use a list, you must declare it first. Do this using square brackets and separate values with commas.
We can construct / create list in many ways. Ex:
>>> list1=[1,2,3,'A','B',7,8,[10,11]]
>>> print(list1)
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]]
8
>>> x=list()
>>> x []
>>> tuple1=(1,2,3,4)
>>> x=list(tuple1)
>>> x
[1, 2, 3, 4]
Variables:
Variables are nothing but reserved memory locations to store values. This means that when you create a variable
you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the
reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals or
characters in these variables.
Rules for Python variables:
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
Variable names are case-sensitive (age, Age and AGE are three different variables)
Assigning Values to Variables:
Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically
when you assign a value to a variable. The equal sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is
the value stored in the variable.
9
For example −
a= 100 # An integer assignment b = 1000.0 # A floating point
c = "John" # A string print (a)
print (b) print (c)
This produces the following result −
100
1000.0
John
Multiple Assignment:
Python allows you to assign a single value to several variables simultaneously. For example :
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned to the same memory
location. You can also assign multiple objects to multiple variables.
For example −
a,b,c = 1,2,"TECHIN IT“
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string object
with the value "john" is assigned to the variable c.
Output Variables:
The Python print statement is often used to output variables.
Variables do not need to be declared with any particular type and can even change type after they have been set.
10
Expressions:
An expression is a combination of values, variables, and operators. An expression is evaluated using assignment
operator.
Examples: Y=x + 17
>>> x=10
>>> z=x+20
>>> z 30
>>> x=10
>>> y=20
>>> c=x+y
>>> c 30
A value all by itself is a simple expression, and so is a variable.
>>> y=20
>>> y 20
Python also defines expressions only contain identifiers, literals, and operators. So,
Identifiers: Any name that is used to define a class, function, variable module, or object is an identifier.
Literals: These are language-independent terms in Python and should exist independently in any programming
language. In Python, there are the string literals, byte literals, integer literals, floating point literals, and imaginary
literals.
Operators: In Python you can implement the following operations using the corresponding tokens.
11
Operator Token
Add +
Subtract -
Multiply *
Integer Division /
Remainder %
And &
Or \
Check equality ==
12
Comments:
Single-line comments begins with a hash(#) symbol and is useful in mentioning that the whole line should be
considered as a comment until the end of line.
A Multi line comment is useful when we need to comment on many lines. In python, triple double quote(“ “ “)
and single quote(‘ ‘ ‘)are used for multi-line commenting.
Example:
Output:
C:/Users/TECHIN IT/AppData/Local/Programs/Python/Python38-32/pyyy/comm.py 30
13
Modules:
Modules: Python module can be defined as a python program file which contains a python code including python
functions, class, or variables. In other words, we can say that our python code file saved with the extension (.py) is
treated as the module. We may have a runnable code inside the python module. A module in Python provides us
the flexibility to organize the code in a logical way. To use the functionality of one module into another, we must
have to import the specific module.
Syntax:
import <module-name>
Every module has its own functions, those can be accessed with . (dot)
Note: In python we have help ()
Enter the name of any module, keyword, or topic to get help on writing Python programs and using Python
modules. To quit this help utility and return to the interpreter, just type "quit".
Some of the modules like os, date, and calendar so on……
>>> import sys
>>> print(sys.version)
3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)]
>>> print(sys.version_info)
sys.version_info(major=3, minor=8, micro=0, releaselevel='final', serial=0)
>>> print(calendar.month(2021,5))
14
Functions:
Functions and its use: Function is a group of related statements that perform a specific task. Functions help break
our program into smaller and modular chunks. As our program grows larger and larger, functions make it more
organized and manageable. It avoids repetition and makes code reusable.
Built-in functions - Functions that are built into Python. Ex: abs(),all().ascii(),bool()………so on….
integer = -20
Output:
Output:
The sum is 25
Flow of Execution:
The order in which statements are executed is called the flow of execution
Execution always begins at the first statement of the program.
Statements are executed one at a time, in order, from top to bottom.
Function definitions do not alter the flow of execution of the program, but remember that statements inside the
function are not executed until the function is called.
Function calls are like a bypass in the flow of execution. Instead of going to the next statement, the flow jumps to
the first line of the called function, executes all the statements there, and then comes back to pick up where it left
off.
15
Note: When you read a program, don’t read from top to bottom. Instead, follow the flow of execution. This means
that you will read the def statements as you are scanning from top to bottom, but you should skip the statements of
the function definition until you reach a point where that function is called.
Example:
#example for flow of execution
print("welcome") for x in range(3):
print(x)
print("Good morning college")
Output:
C:/Users/TECHIN IT/AppData/Local/Programs/Python/Python38-32/pyyy/flowof.py welcome
0
1
2
Good morning college
The flow/order of execution is: 2,3,4,3,4,3,4,5
16
Output:
C:/Users/TECHIN IT/AppData/Local/Programs/Python/Python38-32/pyyy/flowof.py hi
hello
Good morning TECHIN IT
done!
The flow/order of execution is: 2,5,6,7,2,3,4,7,8
Parameters are passed during the definition of function while Arguments are passed during the function call.
Example:
#here a and b are parameters
Output:
C:/Users/TECHIN IT/AppData/Local/Programs/Python/Python38-32/pyyy/paraarg.py 25
There are three types of Python function arguments using which we can call a function.
Default Arguments
Keyword Arguments
Variable-length Arguments
Syntax:
def functionname():
17
statements
.
.
.
functionname()
Example:
Syntax:
def function name(parameters):
#function body(statements)
Return expression
18
The return statement is used to exit a function and go back to the place from where it was called. This statement
can contain expression which gets evaluated and the value is returned. If there is no expression in the statement or
the return statement itself is not present inside a function, then the function will return the None object.
19
# Passing Arguments
Syntax:
def function_name(parameter1:data_type,paramete2:data_type…):
Body of the function
Return expression
Ex:
def add(num1:int,num2:int):
#add two numbers
num3=num1+num2
Return num3
#drive code
ans=add(5,15)
#Keyword Arguments
When we call a function with some values, these values get assigned to the arguments according to their
position.
Python allows functions to be called using keyword arguments. When we call functions in this way, the order
(position) of the arguments can be changed.
In this arguments are assigned based on the name of arguments
Ex. def display_info(first_name,last_name):
print(“firstname:”,first_name)
print(“lastname:”,last_name)
display_info(last_name=’mohammad’,first_name=’majed’)
def find_sum(*num):
result=0
for i in num:
result=result+i
return result
#function call with 3 args
add_result=find_sum(1,2,3)
print("sum=",add_result)
#function call with 2 args
add_result1=find_sum(4,9)
print("sum two args",add_result1)
o/p;
sum=6
sum=13
20
Python Recursive Function
In Python, we know that a function can call other functions. It is even possible for the function to call itself. These
types of construct are termed as recursive functions.
The following image shows the working of a recursive function called recurse.
3!=3*2*1=6
def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x *factorial(x-1))
Output
The factorial of 3 is 6
factorial(3) # 1st call with 3
3 * factorial(2) # 2nd call with 2
3 * 2 * factorial(1) # 3rd call with 1
3*2*1 # return from 3rd call as number=1
3*2 # return from 2nd call
6 # return from 1st call
21
Lambda function:
Ex.
greet =lambda : print(‘hello world’)
print(x)
def my_fun1():
x=400
print(x)
my_fun1()
2.Global scope:
A variable created in the main body of the python code is a global variable and belongs to the global scope
*global variables are available from within any scope,global and local
Conditional statements:
If else
Nested if else
Elif
1.If else
Syntax:
If condition:
Do this(block of statements)
Else:
Do this(block of statements)
ex:water_level=50
If water_level>=80:
print(“drain water”)
23
Else:
print(“continue”)
2Nested if else
Syntax:
If condition1:
If another condition2:
Do this.block1
Else:
Do this…..block2
Else:
Do this…..block3
3.ELIF:
24
If condition1:
Block1
Elif condition2:
Block2
Else
block3
Looping statements:
Looping statements executes block of statements no of times until condition becomes false.
Python supports 3 types loop statements:
25
1.while loop
2.for loop
3.nested loop
1.while loop:
While loop executes block of statements based on condition it will execute statements until condition becomes falls
Syntax:
while <condition>:
{blok of statements }
Ex.counter=0
While counter<10
counter=counter+3
print(“print loop”)
For loop:
For loop used to iterate block of statement
26
Syntax:
For variable in collection:
{code block }
ex.
To print square of given list values.
numbers=[4,2,6,7,3,5,8,10,6,1,9,2]
square=0
#variable to store the square of the no
27
For i in numbers:
square=i**2
squares.append(square)
Print("this is square value is",squares)
# append function syntax:
list or tuple or dictionary name.append(variable)
o/p;
This is square value is [16]
This is square value is [16,4]
This is square value is [16,4,]
This is square value is [16,4,36]
n=int(input(“enter n value”))
i=0
While i<=n:
If i%2==0:
print(“even no is”,i)
i+=2
Output:
Enter n value 100
Even no is 0
Even no is 2
Even no is 4
Even no is 6
Even no is 8
Even no is 10
Even no is 12
n=int(input(“enter n value”))
For i in range(n):
If i%2==0:
print(i)
Output:
0
2
4
6
8
10
28
#range(start,stop,step)
#range(0,10,1)
n=int(input(“enter n value”))
i=2
While i<=n:
If i%2==0:
j=i**2
print(“even number square is”,j)
i+=2
Output:
Even number square is 4
Even number square is 16
Even number square is 36
Even number square is 64
Even number square is 100
Even number square is 144
Even number square is 196
Write a python programme to print squares of n even numbers? for loop.
29
Break and continue:
In Python, break and continue statements can alter the flow of a normal loop. Sometimes we wish to terminate the
current iteration or even the whole loop without checking test expression. The break and continue statements are
used in these cases.
Break:
The break statement terminates the loop containing it and control of the program flows to the statement
immediately after the body of the loop. If break statement is inside a nested loop (loop inside another loop), break
will terminate the innermost loop.
Flowchart:
The following shows the working of break statement in for and while loop:
for var in sequence:
# code inside for loop If condition:
break (if break condition satisfies it jumps to outside loop) # code inside for loop
# code outside for loop
30
while test expression
# code inside while loop If condition:
break (if break condition satisfies it jumps to outside loop) # code inside while loop
# code outside while loop
Example:
for val in "TECHIN IT COLLEGE": if val == " ":
break print(val)
print("The end")
Output:
MRCET
The end
Output:
11
9
88
The number 88 is found
31
Terminating the loop
#
for letter in "Python": # First Example if letter == "h":
break
print("Current Letter :", letter )
Output:
C:/Users/TECHIN IT/AppData/Local/Programs/Python/Python38-32/pyyy/br.py = Current Letter : P
Current Letter : y Current Letter : t Continue:
The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not
terminate but continues on with the next iteration.
Flowchart:
The following shows the working of break statement in for and while loop:
32
for var in sequence:
# code inside for loop If condition:
continue (if break condition satisfies it jumps to outside loop) # code inside for loop
# code outside for loop
Example:
# Program to show the use of continue statement inside loops
# program to display only odd numbers for num in [20, 11, 9, 66, 4, 89, 44]:
33
# Skipping the iteration when number is even if num%2 == 0:
continue
# This statement will be skipped for all even numbers print(num)
Output:
C:/Users/TECHIN IT/AppData/Local/Programs/Python/Python38-32/pyyy/cont2.py 11
9
89
#
for letter in "Python": # First Example if letter == "h":
continue
print("Current Letter :", letter) Output:
Pass:
In Python programming, pass is a null statement. The difference between a comment and pass
statement in Python is that, while the interpreter ignores a comment entirely, pass is not ignored.
pass is just a placeholder for functionality to be added later.
Example:
sequence = {'p', 'a', 's', 's'} for val in sequence:
pass
Output:
C:/Users/TECHIN IT/AppData/Local/Programs/Python/Python38-32/pyyy/f1.y.py
34
>>>
def f(arg): pass # a function that does nothing (yet) class C: pass # a class with no methods (yet)
String module:
This module contains a number of functions to process standard Python strings. In recent versions, most
functions are available as string methods as well.
It’s a built-in module and we have to import it before using any of its constants and classes Syntax: import string
Note:
help(string) --- gives the information about all the variables ,functions, attributes and classes to be used in string
module.
Example:
import string print(string.ascii_letters) print(string.ascii_lowercase) print(string.ascii_uppercase) print(string.digits)
print(string.hexdigits) print(string.whitespace) print(string.punctuation)
Output:
C:/Users/TECHIN IT/AppData/Local/Programs/Python/Python38-32/pyyy/strrmodl.py
=========================================
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
0123456789abcdefABCDEF
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
Python arrays:
Array is a container which can hold a fix number of items and these items should be of the same type. Most of the
data structures make use of arrays to implement their algorithms. Following are the important terms to understand
the concept of Array.
Array Representation
Arrays can be declared in various ways in different languages. Below is an illustration.
Elements
Int array [10] = {10, 20, 30, 40, 50, 60, 70, 80, 85, 90}
As per the above illustration, following are the important points to be considered.
Index starts with 0.
Array length is 10 which means it can store 10 elements.
35
Each element can be accessed via its index. For example, we can fetch an element at index 6 as 70
Basic Operations
Typecode Value
36
c Represents character of size 1 byte
Creating an array:
from array import *
array1 = array('i', [10,20,30,40,50]) for x in array1:
print(x)
Output:
>>>
RESTART: C:/Users/TECHIN IT/AppData/Local/Programs/Python/Python38-32/arr.py 10
20
30
40
50
37
Output:
RESTART: C:/Users/TECHIN IT/AppData/Local/Programs/Python/Python38-32/pyyy/arr2.py 10
30
Array methods:
Python has a set of built-in methods that you can use on lists/arrays.
Method Description
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
38
LISTS, TUPLES, DICTIONARIES
Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list parameters, list
comprehension; Tuples: tuple assignment, tuple as return value, tuple comprehension; Dictionaries: operations and
methods, comprehension;
Lists, Tuples, Dictionaries:
List:
It is a general purpose most widely used in data structures
List is a collection which is ordered and changeable and allows duplicate members. (Grow and shrink as
needed, sequence type, sortable).
To use a list, you must declare it first. Do this using square brackets and separate values with commas.
We can construct / create list in many ways. Ex:
>>> list1=[1,2,3,'A','B',7,8,[10,11]]
>>> print(list1)
[1, 2, 3, 'A', 'B', 7, 8, [10, 11]]
>>> x=list()
>>> x []
>>> tuple1=(1,2,3,4)
>>> x=list(tuple1)
>>> x
[1, 2, 3, 4]
39
List operations:
These operations includeindexing, slicing,adding,multiplying, and checking for membership
Lists respond to the + and * operators much like strings; they mean concatenation and repetition here too,
except that the result is a new list, not a string.
Because lists are sequences, indexing and slicing work the same way for lists as they do for strings.
Assuming following input −
L = ['TECHIN IT', 'college', 'TECHIN IT!']
40
L[-2] college Negative: count from the right
Aliasing:
An alias is a second name for a piece of data, often easier (and more useful) than making a copy.
If the data is immutable, aliases don’t matter because the data can’t change.
But if data can change, aliases can result in lot of hard – to – find bugs.
Aliasing happens whenever one variable’s value is assigned to another variable.
For ex:
a = [81, 82, 83]
Tuples:
A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets.
Supports all operations for sequences.
Immutable, but member objects may be mutable.
If the contents of a list shouldn’t change, use a tuple to prevent items from
accidently being added, changed, or deleted.
Tuples are more efficient than list due to python’s implementation.
Example:
>>> x=(1,2,3)
>>> print(x) (1, 2, 3)
>>> x (1, 2, 3)
>>> x=()
>>> x ()
>>> x=[4,5,66,9]
>>> y=tuple(x)
>>> y
(4, 5, 66, 9)
>>> x=1,2,3,4
>>> x
(1, 2, 3, 4)
41
Some of the operations of tuple are:
Access tuple items
Change tuple items
Loop through a tuple
Count()
Index()
Length()
42
Access tuple items: Access tuple items by referring to the index number, inside square brackets
>>> x=('a','b','c','g')
>>> print(x[2]) c
Change tuple items: Once a tuple is created, you cannot change its values. Tuples are unchangeable.
>>> x=(2,5,7,'4',8)
>>> x[1]=10
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module> x[1]=10
TypeError: 'tuple' object does not support item assignment
>>> x
(2, 5, 7, '4', 8) # the value is still the same
Loop through a tuple: We can loop the values of tuple using for loop
>>> x=4,5,6,7,2,'aa'
>>> for i in x:
print(i)
4
5
6
7
2
aa
Count (): Returns the number of times a specified value occurs in a tuple
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> x.count(2) 4
Index (): Searches the tuple for a specified value and returns the position of where it was found
43
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> x.index(2) 1
(Or)
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=x.index(2)
>>> print(y) 1
Length (): To know the number of items or values present in a tuple, we use len().
>>> x=(1,2,3,4,5,6,2,10,2,11,12,2)
>>> y=len(x)
>>> print(y) 12
Tuple Assignment
Python has tuple assignment feature which enables you to assign more than one variable at a time. In here, we have
assigned tuple 1 with the college information like college name, year, etc. and another tuple 2 with the values in it
like number (1, 2, 3… 7).
For Example, Here is the code,
>>> tup1 = ('TECHIN IT', 'eng college','2004','cse', 'it','csit');
>>> tup2 = (1,2,3,4,5,6,7);
>>> print(tup1[0])
TECHIN IT
>>> print(tup2[1:4])
(2, 3, 4)
Tuple 1 includes list of information of TECHIN IT Tuple 2 includes list of numbers in it
Dictionaries:
A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with
curly brackets, and they have keys and values.
Key-value pairs
Unordered
We can construct or create dictionary like:
X={1:’A’,2:’B’,3:’c’}
X=dict([(‘a’,3) (‘b’,4)] X=dict(‘A’=1,’B’ =2)
Example:
>>> dict1 = {"brand":"TECHIN IT","model":"college","year":2004}
>>> dict1
{'brand': 'TECHIN IT', 'model': 'college', 'year': 2004}
44
Classes and objects:
OOP:
Object oriented programming
Object:
Real world entity of a class
Instance of a class
Attribute: variables
🚗 Is an object
Attributes:
Speed=0
Fuel=6
Methods:
Drive()
Speed ()
Cam()
Gps()
Creating a class:
Syntax:
Class <classname>:
Attributes
Methods
Creating object:
Syntax:
Ex
class CarBluePrint
Speed=0
Fuel=5
def Drive()
Print("drive within limit")
def Speed()
Print("don't over speed")
#object =class name()
Car=CarBluePrint() 45
Car.speed=40
Car.fuel =5
Car.Drive()
Car.speed()
Programme: create turtle 🐢 with coral color and move 100 and draw same color line.
06/06/2023
Constructor:
In python constructor is a special type of method executed at the time of object creation.
Class CarBluePrint:
Attributes
Methods
car=CarBluePrint()#constuctor
_ _init_ _ method:
1.For every class defination init method exist for variable declaration.
2.When ever an object created for a class init will be executed.
3.It is a default initiavilzer method
For every class
4.It is specialy designed for attributes initialisation
Syntax.
_ _init_ _(self,params)
Ex.
class CarBluePrint
def _init_(self,seats,fuel)
self.seats=5
self.fuel=6
Resources={water:water, coffee:cofee,milk:milk}
Inheritance : 46
Inheritance is a core concept of python which allow to derive super class properties and
methods to subclass
Syntax.
class Subclass name (super class name):
Ex
Class Animal:
def _ _init_ _(self):
Self.num_eyes=2
def breath(self):
Print("inhele,exhile")
class Fish(Animal):
def _ _init_ _(self): super._ _init_ _(self):
Super.breath()
…..,
…..
08/06/23
Python Inheritance
Inheritance is an important aspect of the object-oriented paradigm. Inheritance provides code
reusability to the program because we can use an existing class to create a new class instead
of creating it from scratch.
In inheritance, the child class acquires the properties and can access all the data members and
functions defined in the parent class. A child class can also provide its specific
implementation to the functions of the parent class. In this section of the tutorial, we will
discuss inheritance in detail.
In python, a derived class can inherit base class by just mentioning the base in the bracket
after the derived class name. Consider the following syntax to inherit a base class into the
derived class.
Python Inheritance
Syntax
A class can inherit multiple classes by mentioning all of them inside the bracket. Consider the
following syntax.
Syntax
class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
<class - suite>
Example 1 47
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak()
ADVERTISEMENT
ADVERTISEMENT
Output:
dog barking
Animal Speaking
Base class
!
Child class1
!
Child class2
.
.
Python Inheritance
The syntax of multi-level inheritance is given below.
Syntax
class class1:
<class-suite>
class class2(class1):
<class suite>
class class3(class2):
<class suite>
.
.
class Animal:
def speak(self):
print("Animal Speaking")
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self): 48
print("dog barking")
#The child class Dogchild inherits another child class Dog
class DogChild(Dog):
def eat(self):
print("Eating bread...")
d = DogChild()
d.bark()
d.speak()
d.eat()
Output:
dog barking
Animal Speaking
Eating bread…
Python provides us the flexibility to inherit multiple base classes in the child class.
Python Inheritance
The syntax to perform multiple inheritance is given below.
Syntax
class Base1:
<class-suite>
class Base2:
<class-suite>
.
.
.
class BaseN:
<class-suite>
Example
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(issubclass(Derived,Calculation2))
print(issubclass(Calculation1,Calculation2))
Output:
True
False
The isinstance() method is used to check the relationship between the objects and classes. It
returns true if the first parameter, i.e., obj is the instance of the second parameter, i.e., class.
Example
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(isinstance(d,Derived))
Output:
True 50
Method Overriding
We can provide some specific implementation of the parent class method in our child class.
When the parent class method is defined in the child class with some specific
implementation, then the concept is called method overriding. We may need to perform
method overriding in the scenario where the different definition of a parent class method is
needed in the child class.
Example
class Animal:
def speak(self):
print("speaking")
class Dog(Animal):
def speak(self):
print("Barking")
d = Dog()
d.speak()
Output:
Barking
3.Hierarchical Inheritance:
When more than one derived class are created from a single base this type of inheritance is
called hierarchical inheritance. In this program, we have a parent (base) class and two child
(derived) classes.
Example:
# Base class
class Parent:
def func1(self):
print("This function is in parent class.")
# Derived class1
class Child1(Parent): 51
def func2(self):
print("This function is in child 1.")
# Derivied class2
class Child2(Parent):
def func3(self):
print("This function is in child 2.")
# Driver's code
object1 = Child1()
object2 = Child2()
object1.func1()
object1.func2()
object2.func1()
object2.func3()
Output:
Example:
class School:
def func1(self):
print("This function is in school.")
class Student1(School):
def func2(self):
print("This function is in student 1. ")
class Student2(School):
def func3(self):
print("This function is in student 2.")
52
class Student3(Student1, School):
def func4(self):
print("This function is in student 3.")
# Driver's code
object = Student3()
object.func1()
object.func2()
Output:
4. Hybrid Inheritance:
Inheritance consisting of multiple types of inheritance is called hybrid inheritance.
Example:
class School:
def func1(self):
print("This function is in school.")
class Student1(School):
def func2(self):
print("This function is in student 1. ")
class Student2(School):
def func3(self):
print("This function is in student 2.")
# Driver's code
object = Student3()
object.func1()
object.func2()
Output:
pattern, which allows you to traverse a container and access its elements. The iterator pattern
decouples the iteration algorithms from container data structures.
Polymorphism:
Polymorphism means poly is Greek word it means many morphism means forms
len() function.
To calculate length of given variable
len("india")
5
len([10,12,6,7])
4
len() same function but using with different argument type .
Ex def add(a,b,c)
Return a+b+c
X=add(10,20)
Y=add(4,5,10)
class India():
def capital(self):
print("New Delhi is the capital of India.")
def language(self):
print("Hindi is the most widely spoken language of India.")
def type(self):
print("India is a developing country.")
class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")
def language(self):
print("English is the primary language of USA.")
def type(self):
print("USA is a developed country.")
obj_ind = India()
obj_usa = USA()
for country in (obj_ind, obj_usa):
country.capital()
country.language()
country.type()
Output
New Delhi is the capital of India.
Hindi is the most widely spoken language of India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.
Polymorphism with Inheritance:
In Python, Polymorphism lets us define methods in the child class that have the same name as
the methods in the parent class. In inheritance, the child class inherits the methods from the
parent class. However, it is possible to modify a method in a child class that it has inherited
from the parent class. This is particularly useful in cases where the method inherited from the
parent class doesn’t quite fit the child class. In such cases, we re-implement the method in the
child class. This process of re-implementing a method in the child class is known as Method
Overriding.
class Bird:
def intro(self):
print("There are many types of birds.") 55
def flight(self):
print("Most of the birds can fly but some cannot.")
class sparrow(Bird):
def flight(self):
print("Sparrows can fly.")
class ostrich(Bird):
def flight(self):
print("Ostriches cannot fly.")
obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()
obj_bird.intro()
obj_bird.flight()
obj_spr.intro()
obj_spr.flight()
obj_ost.intro()
obj_ost.flight()
Output
There are many types of birds.
Most of the birds can fly but some cannot.
There are many types of birds.
Sparrows can fly.
There are many types of birds.
Ostriches cannot fly.
class India():
def capital(self):
print("New Delhi is the capital of India.")
def language(self):
print("Hindi is the most widely spoken language of India.")
def type(self):
print("India is a developing country.")
class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")
def language(self):
print("English is the primary language of USA.")56
def type(self):
print("USA is a developed country.")
obj_ind = India()
obj_usa = USA()
for country in (obj_ind, obj_usa):
country.capital()
country.language()
country.type()
Output
New Delhi is the capital of India.
Hindi is the most widely spoken language of India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.
In Python, Polymorphism lets us define methods in the child class that have the same name as
the methods in the parent class. In inheritance, the child class inherits the methods from the
parent class. However, it is possible to modify a method in a child class that it has inherited
from the parent class. This is particularly useful in cases where the method inherited from the
parent class doesn’t quite fit the child class. In such cases, we re-implement the method in the
child class. This process of re-implementing a method in the child class is known as Method
Overriding.
class Bird:
def intro(self):
print("There are many types of birds.")
def flight(self):
print("Most of the birds can fly but some cannot.")
class sparrow(Bird):
def flight(self): 57
print("Sparrows can fly.")
class ostrich(Bird):
def flight(self):
print("Ostriches cannot fly.")
obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()
obj_bird.intro()
obj_bird.flight()
obj_spr.intro()
obj_spr.flight()
obj_ost.intro()
obj_ost.flight()
Python Modules
In this tutorial, you will learn to create and import custom modules in Python. Also, you will
find different techniques to import and use custom and built-in modules in Python.
As our program grows bigger, it may contain many lines of code. Instead of putting
everything in a single file, we can use modules to separate codes in separate files as per their
functionality. This makes our code organized and easier to maintain.
Module is a file that contains code to perform a specific task. A module may contain
variables, functions, classes etc. Let's see an example,
result = a + b
return result
Here, we have defined a function add() inside a module . The function takes in two numbers
and returns their sum.
We use the import keyword to do this. To import our previously defined module example, we
type the following in the Python prompt.
58
Using the module name we can access the function using the dot . operator. For example:
addition.add(4,5) # returns 9
Note:
Suppose we want to get the value of pi, first we import the math module and use math.pi. For
example,
print(m.pi)
# Output: 3.141592653589793
Run Code
Here, We have renamed the math module as m. This can save us typing time in some cases.
Note that the name math is not recognized in our scope. Hence, math.pi is invalid, and m.pi is
the correct implementation.
print(pi)
# Output: 3.141592653589793
Run Code
Here, we imported only the pi attribute from the math module.
59
Import all names
In Python, we can import all names(definitions) from a module using the following construct:
Importing everything with the asterisk (*) symbol is not a good programming practice. This
can lead to duplicate definitions for an identifier.
Python datetime
In this tutorial, we will learn to manipulate date and time in Python with the help of
examples.
Python has a module named datetime to work with dates and times.
It provides a variety of classes for representing and manipulating dates and times, as well as
for formatting and parsing dates and times in a variety of formats.
print(now)
Run Code
Output
2022-12-27 08:26:49.219717
Here, we have imported the datetime module using the import datetime statement.
One of the classes defined in the datetime module is the datetime class.
We then used the now() method to create a datetime object containing the current local date
and time.
print(current_date)
Run Code
Output 60
2022-12-27
In the above example, we have used the today() method defined in the date class to get a date
object containing the current local date.
import datetime
print(dir(datetime))
Run Code
Output
Python has a module named datetime to work with dates and times.
It provides a variety of classes for representing and manipulating dates and times, as well as
for formatting and parsing dates and times in a variety of formats.
2022-12-25
Here, date() in the above example is a constructor of the date class. The constructor takes
three arguments: year, month and day.
2022-12-25
Here, from datetime import date only imports the date class from the datetime module.
A Unix timestamp is the number of seconds between a particular date and January 1, 1970 at
UTC. You can convert a timestamp to date using the fromtimestamp() method.
timestamp = date.fromtimestamp(1326244364)
print("Date =", timestamp)
Run Code
Output
Date = 2012-01-11
Example 6: Print today's year, month and day
We can get year, month, day, day of the week etc. from the date object easily. For example,
`
Python strftime() Method
The strftime() method is defined under classes date, datetime and time. The method creates a
formatted string from a given date, datetime or time object.
t = now.strftime("%H:%M:%S")
print("Time:", t)
s1 = now.strftime("%m/%d/%Y, %H:%M:%S")
# mm/dd/YY H:M:S format
print("s1:", s1)
s2 = now.strftime("%d/%m/%Y, %H:%M:%S")
# dd/mm/YY H:M:S format
print("s2:", s2)
Run Code
Output
time: 04:34:52
s1: 12/26/2018, 04:34:52
s2: 26/12/2018, 04:34:52
Here, %Y, %m, %d, %H etc. are format codes. The strftime() method takes one or more
format codes and returns a formatted string based on it.
A RegEx, or Regular Expression, is a sequence of63 characters that forms a search pattern.
RegEx can be used to check if a string contains the specified search pattern.
RegEx Module
Python has a built-in package called re, which can be used to work with Regular
Expressions.
Import the re module:
import re
RegEx in Python
When you have imported the re module, you can start using regular expressions:
Search the string to see if it starts with "The" and ends with "Spain":
import re
split Returns a list where the string has been split at each match
Metacharacters
Metacharacters are characters with a special meaning:
Character Description Example
\ Signals a special sequence (can also be used to escape special characters) "\d"
| Either or "falls|stays"
pattern = '^a...s$'
test_string = 'abyss'
result = re.match(pattern, test_string)
if result:
print("Search successful.")
else:
print("Search unsuccessful.")
output:
Search successful.
Python pip
What is pip?
pip is the standard package manager for Python. We can use pip to install additional packages
that are not available in the Python standard library. For example,
If we had installed pip on our system, this command would have installed the numpy library.
pip comes pre-installed on the Python versions 3.4 or older. We can check if pip is installed
by using the following command in the console:
pip –version
If pip is already available in the system, the respective pip version is displayed, like:
pip 19.3.1 from C:\Python37\lib\site-packages\pip (python 3.7)
If we are using an older version of Python or do not have pip installed for some other reason,
follow the steps as described in this link
Using pip
pip is a command-line program. After its installation, a pip command is added which can be
used with the command prompt. 65
The basic syntax of pip is:
pip <pip arguments>
Apart from the standard Python library, the Python community contributes to an extensive
number of packages tailored for various development frameworks, tools, and libraries.
Most of these packages are officially hosted and published to the Python Package
Index(PyPI). pip allows us to download and install these packages.
The install command used to install packages using pip. Let's take an example:
Suppose we want to install requests, a popular HTTP library for Python. We can do it with
the help of the following command.
Here, we can see that the pip has been used with the install command followed by the
name of the package we want to install (requests).
The pip list command can be used to list all the available packages in the current Python
environment.
pip list
Output
Package Version
---------- ----------
certifi 2019.11.28
chardet 3.0.4
idna 2.8
pip 19.3.1
requests 2.22.0
setuptools 45.0.0
urllib3 1.25.7
wheel 0.33.6
result = numerator/denominator
print(result)
except:
print("Error: Denominator cannot be 0.")
even_numbers = [2,4,6,8]
print(even_numbers[5])
except ZeroDivisionError:
print("Denominator cannot be 0.")
except IndexError:
print("Index Out of Bound.")
Python try...finally
In Python, the finally block is always executed no matter whether there is an exception or not.
The finally block is optional. And, for each try block, there can be only one finally block.
Let's see an example,
try:
numerator = 10
denominator = 0
result = numerator/denominator
print(result)
except:
print("Error: Denominator cannot be 0.")
finally:
print("This is finally block.")
Run Code
Output
Error: Denominator cannot be 0.
This is finally block.
68
Different Modes to Open a File in Python
Mode Description
Open a file for writing. Creates a new file if it does not exist or truncates the file if it
w
exists.
x Open a file for exclusive creation. If the file already exists, the operation fails.
Open a file for appending at the end of the file without truncating it. Creates a new file
a
if it does not exist.
Open a file for writing. Creates a new file if it does not exist or truncates the file if it
w
exists.
x Open a file for exclusive creation. If the file already exists, the operation fails.
Open a file for appending at the end of the file without truncating it. Creates a new file
a
if it does not exist.
70
Project
71
flash card:
Programme:
import random
class flashcard:
def __init__(self):
self.fruits={'apple':'red',
'orange':'orange',
'watermelon':'green',
'banana':'yellow'}
def quiz(self):
while (True):
if(user_answer.lower() == color):
print("Correct answer")
else:
print("Wrong answer")
Output: 72
welcome to fruit quiz
What is the color of orange
ornage
Wrong answer
enter 0 , if you want to play again : 0
What is the color of watermelon
Green
Correct answer
enter 0 , if you want to play again : 0
73