Python Manual
Python Manual
Python Programming
(IT23202)
Semester– IV
Certificate
Preface
The primary focus of any engineering laboratory/field work in the technical education
system is to develop the much needed industry relevant competencies and skills. With this
in view, MSBTE embarked on this innovative ‘I’ Scheme curricula for engineering Diploma
programmes with outcome-based education as the focus and accordingly, relatively large
amount of time is allotted for the practical work. This displays the great importance of
laboratory work making each teacher, instructor and student to realize that every minute
of thelaboratory time need to be effectively utilized to develop these outcomes, rather
than doing other mundane activities. Therefore, for the successful implementation of this
outcome-based curriculum, every practical has been designed to serve as a ‘vehicle’ to
develop this industry identified competency in every student. The practical skills are
difficult to develop through ‘chalk and duster’ activity in the classroom situation.
Accordingly, the ‘I’ scheme laboratory manual development team designed the practical’s
to focus on outcomes, rather than the traditional age old practice of conducting practical’s
to ‘verify the theory’ (which may becomea by-product along the way).
This laboratory manual is designed to help all stakeholders, especially the students,
teachers and instructors to develop in the student the pre-determined outcomes. It is
expected fromeach student that at least a day in advance, they have to thoroughly read
the concerned practical procedure that they will do the next day and understand
minimum theoretical background associated with the practical. Every practical in this
manual begins by identifying the competency, industry relevant skills, course outcomes
and practical outcomes which serveas a key focal point for doing the practical. Students
will then become aware about the skills they will achieve through procedure shown there
and necessary precautions to be taken, whichwill help them to apply in solving real-world
problems in their professional life.
This manual also provides guidelines to teachers and instructors to effectively facilitate
student-centered lab activities through each practical exercise by arranging and managing
necessary resources in order that the students follow the procedures and precautions
systematically ensuring the achievement of outcomes in the students.
Although all care has been taken to check for mistakes in this laboratory manual, yet it is
impossible to claim perfection especially as this is the first edition. Any such errors and
suggestions for improvement can be brought to our notice and are highly welcome.
Following programme outcomes are expected to be achieved significantly out of the ten
programme outcomes and Computer Engineering programme specific outcomes through
the practical’s of the course on Python Programming
PO1 Basic and Discipline specific knowledge: Apply knowledge of basic mathematics, science
and engineering fundamentals and engineering specialization to solve the engineering
problems.
PO2 Problem analysis: Identify and analyze well-defined engineering problems using codified
standard methods.
PO3 Design/ development of solutions: Design solutions for well-defined technical problems
and assist with the design of systems components or processes to meet specified needs.
PO4 Engineering Tools, Experimentation and Testing: Apply modern engineering tools and
appropriate technique to conduct standard tests and measurements.
PO7 Life-long learning: Ability to analyze individual needs and engage in updating in the
context of technological changes.
PSO1 The student should do programming, database management, networking, web design,
Information Security, Cyber Security and recognize the need for independent and lifelong
learning in the era of fast changing Information technology.
PSO2 The Student should apply knowledge to solve problems through tools with understanding of
social, ethical and environmental context.
PSO3 The student should Analyze Computing problems and find solutions as an individual and can
work in a team as a member or team leader.
The following industry relevant skills of the competency “Develop general purpose
programming using Python to solve problem” are expected to be developed in you by
performing practicals of this laboratory manual.
1. Develop Applications using Python.
2. Write and Execute Python programs using functions, classes and Exception handling
Student shall read the points given below for understanding the theoretical
concepts andpractical applications.
1. Students shall listen carefully the lecture given by teacher about
importance ofsubject, learning structure, course outcomes.
2. Students shall organize the work in the group of two or three members and
make arecord of all observations.
3. Students shall understand the purpose of experiment and its practical
implementation.
4. Students shall write the answers of the questions during practical.
5. Student should feel free to discuss any difficulty faced during the
conduct ofpractical.
6. Students shall develop maintenance skills as expected by the industries.
7. Student shall attempt to develop related hands on skills and gain confidence.
8. Students shall refer technical magazines; websites related to the scope of the
subjectsand update their knowledge and skills.
9. Students shall develop self-learning techniques.
10. Students should develop habit to submit the write-ups on the scheduled
dates andtime.
Content Page
List of Practical’s and Progressive Assessment Sheet
Total Marks
Total Marks (Scaled to 25 Marks)
I. Practical Significance
Python is a high-level, general-purpose, interpreted, interactive, object-oriented
dynamic programming language. Student will able to select and install appropriate
installer for Python in windows and package manager for Linux in order to setup
Python environment for running programs.
Click on next install now for installation and then Setup progress windows
will beopened as shown in Fig. 4.
Fig. 5: Setup
Click on all programs and then click on Python 3.7 (32 bit). You will see
thePython interactive prompt in Python command line.
To exit from the command line of Python, press Ctrl+z followed by Enter or Enter
exit() or quit() and Enter.
You will see the Python interactive prompt i.e. interactive shell.
Python interactive shell prompt contains opening message >>>, called shell
prompt. A cursor is waiting for the command. A complete command is called
a statement. When you write a command and press enter, the Python
Government Polytechnic Mumbai 10
Python Programming (IT19401)
Dated signature
ofTeacher
Bitwise Operators: Bitwise operators acts on bits and performs bit by bit
[Link] a=10 (1010) and b=4 (0100)
Operato Meaning Descriptio Example Output
r n
& Bitwise Operator copies a bit, to the >>>(a&b) 0
AND result,
if it exists in both operands
| Bitwise OR It copies a bit, if it exists in either >>>(a|b) 14
operand.
~ Bitwise It is unary and has the effect of >>>(~a) -11
NOT 'flipping' bits.
^ Bitwise It copies the bit, if it is set in one >>>(a^b) 14
XOR operand but not both.
>> Bitwise The left operand's value is >>>(a>>2) 2
right movedright by the number of
shift bits
specified by the right operand.
<< Bitwise left The left operand's value is moved >>>(a<<2) 40
shift left by the number of bits
specified
by the right operand.
Minimum Theoretical Background
a) IF Statement: if statement is the simplest decision making statement. It is used
to decide whether a certain statement or block of statements will be executed or
not i.e ifa certain condition is true then a block of statement is executed otherwise
not.
Syntax:
If condition:
Statement(
s)
Example:
i=10
if(i > 20):
Government Polytechnic Mumbai 13
Python Programming (IT19401)
c) Nested-if Statement:
A nested if is an if statement that is the target of another if statement. Nested if
statements means an if statement inside another if statement. Yes, Python allows
us to nest if statements within if statements. i.e, we can place an if statement inside
anotherif statement.
Syntax:
if (condition1):
# Executes when condition1 is
trueif (condition2):
# Executes when condition2 is
true# if Block is end here
# if Block is end here
Example:
i =10
if(i ==10):
# First if
statementif(i <
20):
print ("i is smaller than 20")
# Nested - if statement will only be executed if statement above is
trueif (i < 15):
print ("i is smaller than 15 too")
else:
print ("i is greater than 15")
Output:
i is smaller than 20
i is smaller than 15 too
f condition1:
# code block 1
elif condition2:
# code block 2
else:
# code block 3
for x in "banana":
print(x)
i=1
while i < 6:
print(i)
i += 1
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
Dated signature
ofTeacher
Practical Significance
All object oriented programming languages supports reusability. One way to
achieve this is to create a function. Like any other programming languages Python
supports creation of functions and which can be called within program or outside
program. Reusability and Modularity to the Python program can be provided by a
function by calling it multiple times. This practical will make learner use of
modularized programming using functions.
Python Functions
The fundamentals of Python functions, including what they are, their syntax,their primary
parts, return keywords, and major types, will be covered in thistutorial. Additionally, we’ll
examine several instances of Python function definitions.
1. Default argument
2. Keyword arguments (named arguments)
3. Positional arguments
4. Arbitrary arguments (variable-length arguments *args and **kwargs)
Default Arguments
A default argument is a parameter that assumes a default value if a value is not provided in the
function call for that argument. The following example illustratesDefault arguments.
Keyword Arguments
The idea is to allow the caller to specify the argument name with values so thatthe caller
does not need to remember the order of parameters.
Positional Arguments
We used the Position argument during the function call so that the first argument(or value) is
assigned to name and the second argument (or value) is assigned to age. By changing the
position, or if you forget the order of the positions, the
values can be used in the wrong places, as shown in the Case-2 example below,where 27 is
assigned to the name and Suraj is assigned to the age
Example2:
Def myFun(**kwargs):
For key, value in [Link]():
Print(“%s == %s” % (key, value) myFun(first=’Geeks’,
mid=’for’, last=’Geeks’)
Conclusion
Thus from this experiment, we have learned and understand the functionconcept in
python.
Write a Python function that takes a number as a parameter and check the number
isprime or not.
1. Write a Python function to calculate the factorial of a number (a non-
negativeinteger). The function accepts the number as an argument.
2. Write a Python function that accepts a string and calculate the number of
upper caseletters and lower case letters.
Dated signature
ofTeacher
In C++ or Java, the constructor has the same name as its class, but it treatsconstructor differently
in Python. It is used to create an object.
1. prameterized [Link]-
parameterized
Method body
PythonGeeks()
It does not have to be named self , you can call it whatever you like, but ithas
to be the first parameter of any function in the class:
In Python, Class variables are declared when a class is being [Link] are not defined
inside any methods of a class because of this only one copy of the static variable will be created
and shared between all objects of the class.
Codes
# define a class
class Bike:
name = ""
gear = 0
Output:-
2. Constructor:-
class GeekforGeeks:
# default constructor
def init (self):
[Link] = "GeekforGeeks"
Output:-
GeekforGeeks
3. Class Variable:-
class Person:
def init (self, name, age):[Link] =
name
[Link] = age
= Person("John", 36)
print(p1)
Output:-
Name=John
Age= 36
[Link] Variable:-
class student:
# constructor
def init (self, name, rollno):
# instance variable
[Link] = name
[Link] = rollno
def display(self):
# Driver Code
# object created
s = student('HARRY', 1001)
Output:-
Dated signature
ofTeacher
I. Practical Significance
Inheritance allows us to define a class that inherits all the methods and properties
from another class. The existing class is called as Parent class or base class and the
new class which inherited from base class is called Child class or derived class.
The new class is called derived class or child class & the class from which this
derived class has been inherited is the base class or parent class.
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.
Syntax:
class BaseClass1
#Body of base class
class DerivedClass(BaseClass1):
#body of derived - class
Example:
# Parent class
createdclass Parent:
parentname =
""childname =
""
def show_parent(self):
print([Link])
# Child class created inherits Parent
classclass Child(Parent):
def show_child(self):
print([Link]
e)
ch1 = Child() # Object of Child class
[Link] = "Vijay" # Access Parent class
[Link] = "Parth"
ch1.show_parent() # Access Parent class
methodch1.show_child() # Access Child class
method
a) Multiple inheritance
Python provides us the flexibility to inherit multiple base classes in the child class.
Multiple Inheritance means that you're inheriting the property of multiple
classes into one. In case you have two classes, say A and B, and you want to
create a new class which inherits the properties of both A and B.
So it just like a child inherits characteristics from both mother and father, in
Python, we can inherit multiple classes in a single child class.
Government Polytechnic Mumbai 26
Python Programming (IT19401)
Syntax
:
Syntax:
class A:
# variable of class A
# functions of class
A
class B:
# variable of class A
# functions of class
A
class C(A, B):
# class C inheriting property of both class A and
B# add more properties to class C
Example:
class Add:
def
Addition(self,a,b):
return a+b;
class Mul:
def
Multiplication(self,a,b):
return a*b;
class
Derived(Add,Mul):
def Divide(self,a,b):
return
a/b;d =
Derived()
print([Link](10,20))
print([Link](10,2
0))print([Link](10,20))
Output:
30
200
0.5
1. Create a class Employee with data members: name, department and salary.
Createsuitable methods for reading and printing employee information
2. Python program to read and print students information using two classes
usingsimple inheritance.
3. Write a Python program to implement multiple inheritance
Dated signature
ofTeacher
Tkinter:
Python offers multiple options for developing GUI (Graphical User Interface). Out
of all the GUI methods, tkinter is the most commonly used method. It is a standard
Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the
fastest and easiest way to create the GUI applications. Creating a GUI using tkinter is
an easy task.
Set up Tkinter:
To install the Tkinter module run the below command in the terminal.
pip install tk
To import the installed module, we import all the methods in the Tkinter library by
using *:
from tkinter import *
root = Tk()
canvas = Canvas()
[Link]()
2]Canvas(): It is used to draw pictures and other complex layout like graphics, text and
widgets.
The general syntax is:
w =Canvas(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number of
options can be passed as parameters separated by commas. Some of them are listed below.
3] mainloop(): There is a method known by the name mainloop() is used when your
application is ready to run. mainloop() is an infinite loop used to run the application, wait for
an event to occur and process the event as long as the window is not closed.
[Link]()
After initialization of the Tkinter and canvas class, we start with the drawing of different
shapes.
1) Oval: Oval can be easily drawn using the create_oval() method. This method takes
coordinates, color, outline, width, etc. as a parameter. All shapes are created inside a box
whose coordinates we provide.
canvas.create_oval(x0, y0, x1, y1)
2. Rectangle:By using the create_rectangle() method we draw a rectangle and square shapes.
Here we pass the edges/sides of our shape and hence can draw a square also, using the same
method (all sides equal).
canvas.create_rectangle(x0,y0,x1,y1)
3. Polygon: We can draw as many vertices as we want. We use the create_polygon() method
which takes coordinates of edges and renders them accordingly on our main window. In the
below code we’ve created a list of coordinates and passed it into our create_polygon method.
canvas.create_polygon(x0,y0,x1,y1,…….)
Program:
Output:
Conclusion:
From this experiment we can conclude tha we learnt to draw different shapes
using different methods on canvas using tkinter.
Dated signature
ofTeacher
Example
1. from tkinter import *
2. top = Tk()
3. frame = Frame(top)
4. [Link]()
5. [Link]()
Frame Layouts
tkinter also offers access to the geometric configuration of the widgets which can
organize the widgets in the parent windows. There are mainlythree geometry
manager classes class.
Widgets:-
Button:-
To add a button in your application, this widget is used.
Example:-
Output :-
Label:
It refers to the display box where you can put any text or image whichcan be updated any
time as per the code.
Example:-
Output :-
Entry:-
It is used to input the single line text entry from the user.. For multi-line text input, Text
widget is used.
Example:-
Output :-
CheckButton:-
Example:-
Output :-
RadioButton:-
It is used to offer multi-choice option to the user. It offers several options tothe user
and the user has to choose one option.
Syntax:- w = RadioButton(master, option=value)
There are number of options which are used to change the format of thiswidget.
Number of options can be passed as parameters separated by commas.
Example:-
Output :-
Listbox:-
It offers a list to the user from which the user can accept any number ofoptions.
Example:-
Output :-
SpinBox:-
Government Polytechnic Mumbai 41
Python Programming (IT19401)
Example:-
Output :-
Scrollbar:-
Example:-
Output :-
Bind() method :-
The binding function is used to deal with the events. We can bind Python’s
Functions and methods to an event aswell as we can bind these functions to any
particular widget…
Example:-
Output :-
Example:-
a=[Link]()
b=[Link]() if
a==1:
str=str+" Year:-FY\n"else:
str=str+"Year :-SY\n"
s=[Link]()
str=str+"SEM:-"+s q=[Link]()
str=str+"\nPassword:-"+q
l=Label(base,text=str)
[Link](x=200,y=500)
#Button
x = Button(base, text="Register",
width=10,bg='brown',fg='white',command =click)
[Link](x=200,y=400)
[Link]()
Output :-
Conclusion:-
Hence from this experiment we have learnt aboutTkinter frame in
python and know how use different types of widget in frame…
Dated signature
ofTeacher
3) a –to append the data to the file. file pointer at end. if file does not exit it will create new
file for writing.
4) w+- to write and read the of file. previous data will be deleted.
5) r+ -to read and write data into a file. the previous data will not not deleted. the file pointer
will be at beginning
6)a+ -to append and read the data of file. the file pointer will be at end if file exists. if not
exist then create new file.
closing of file:
A file which is opened should be closed USING close() method.
[Link]()
program 1:
f=open("[Link]","w")
s=input("enter your name:")
[Link](s)
[Link]()
try:
f=open("[Link]","r")
s=[Link]()
print(s)
[Link]()
except:
print("file not found")
try:
f=open("[Link]","a")
s=input("enter name:")
[Link](s)
[Link]()
except:
print("file not found")
f=open("[Link]","a")
print("enter student names until you enter *")
s=input("name")
while s!='*':
s=input("name")
if(s!='*'):
[Link](s+"\n")
[Link]()
The with statement: the with statement is used while opening the file. the advantage is that
with statement will take care of closing the file which you have open. we need not to close
the file .
with open(“[Link]”,”r”) as f:
[Link](offset,fromwhere)
Exercise:
1. develop program to count no of lines in file
2. develop program to copy the content of line from one to another.
3. Develop program to open binary file
Dated signature
ofTeacher
A regular expression is a string that contains special symbols and characters to find or
extract the information needed by us from the given data.
a regular expression helps us to search ,match, find and split the given data as per
requirement.
it is also called as ‘regex’.it is also in other languages like JAVA,Perl
python provide re module that stands for regular [Link] module contains the
methods like
1)match(): the match() method searches in the beginning of the string .if the matching string
found it returns an object that contains the result otherwise it returns None. we can assess
the string from returned object using group() method.
2)search() : the search() method searches the string from beginning till the end and return
first occurrence of the matching string. otherwise it return None. we use group() method to
retrieve the string from result.
3) findall():the findall() method searches the string from beginning till the endand returns
all occurrences of the matching string in the for of list .if the matching string not found then
it will return empty list. we can use for loop to display result or can directly print list.
4) split()- the split method splits the string according to the regular expression and resultant
pieces are returned as a list. it there are no string pieces then it returns an empty list. we can
print resultant by using for loop.
5) sub(): the sub() method substitutes or replace new strings in place of existing strings
after substitute the main string is returned by this method.
sub(regular expression ,new string, string)
Characters Description
[^...] -Matches every character except the one inside [Link][^a-c6] a,b,c or 6
1) A python program to create a regular expression to retrieve all words starting with a in string
import re
str='an apple a day keeps doctor away'
r=r'a[\w]*'
result=[Link](r,str)
print(result)
2) A python program to create a regular expression to retrieve all words starting with a
numeric digit.
import re
str='the meeting will be at 1st and 2nd day of everymonth'
r=r'\b\d[\w]*\b'
result=[Link](r,str)
for i in result:
print(i)
3) A python program to create a regular expression to retrieve all words
having 5 character length
import re
str='one two three four five six seven eight nine ten'
r=r'\b\w{5}\b'
result=[Link](r,str)
for i in result:
print(i)
4) A python program to create a regular expression to retrieve all the words
having the length of at least 4 characters.
Government Polytechnic Mumbai 51
Python Programming (IT19401)
import re
str='one two three four five six seven eight nine ten'
r=r'\b\w{4,}\b'
result=[Link](r,str)
for i in result:
print(i)
5)A python program to create a regular expression to retrieve all the words
with 3 or 4 or 5 characters.
import re
str='one two three four five six seven eight nine ten be the
part of GPM'
r=r'\b\w{3,5}\b'
result=[Link](r,str)
for i in result:
print(i)
6)A python program to create a regular expression to retrieve only single digit
from a string.
import re
str=' 1 two 3 four 5 six seven 8 9 10'
r=r'\b\d\b'
result=[Link](r,str)
for i in result:
print(i)
05/07/1991 r’\b\d{2}\\d{2}\\d{4}
05-07-1991
5/7/91 r’\d{1,2}-\d{1,2}-\d{4}
5/7/1991
import re
f=open("[Link]","r")
str=[Link]()
r=r'\b\d{1,2}-\d{1,2}-\d{2,4}\b'
res=[Link](r,str)
for i in res:
print(i)
Exercise:
1.A python program to create a regular expression to search whether a given string is
starting with ‘He’ or not
2.A python program to create a regular expression to retrieve marks from a given string.
3.A python program to create a regular expression to retrieve email id from given data
Dated signature
ofTeacher
Students has to apply knowledge of python programming and develop some basic
applications.
Dated signature
ofTeacher