Lab Manual Python - Laboratory - 2022-23
Lab Manual Python - Laboratory - 2022-23
Lab Manual Python - Laboratory - 2022-23
2022-23
Prepared By
Mrs.Bhagyalakshmi.V
Assistant Professors
Department of ECE
MIT Thandavapura
Dept of ECE,MIT 1
Introduction to Python Programming Language BPCLK105B/205B
Students must present a College ID card before entering the python programming lab.
Every user must make an entry in the login book while entering in the python programming lab
and also at the time of exit from the lab.
Students must write the programs in the observation book to be executed and complete the
record writing of previous week observations before entering the Lab.
Users are strictly prohibited from modifying or deleting any important files and install any
software or settings in the computer.
If any problem arises, please bring the same to the notice of lab in-charge.
Students are not allowed to use personal Pen Drives etc., in Lab.
In case of theft / destruction of the computers or peripherals, double the cost of the lost will be
charged from the student/user.
DO NOT leave your personal belongings at the computer. The College is not responsible for
items left behind.
Users must turn-off the computer before leaving the computer lab.
Silence must be maintained in the lab at all times.
The lab must be kept clean and tidy at all times.
Conversation, discussion, loud talking & sleeping are strictly prohibited.
No bags/ hand bags/ rain coats/ casual wears will be allowed inside the python programming
lab, however observation book and lab record may be allowed.
Dept of ECE,MIT 2
Introduction to Python Programming Language BPCLK105B/205B
Python is a popular programming language. It was created by Guido van Rossum, and released in
1991. Python is a high-level, general-purpose programming language. Its design philosophy
emphasizes code readability with the use of significant indentation.
Python is dynamically-typed and garbage-collected. It supports multiple programming paradigms,
including structured (particularly procedural), object-oriented and functional programming. It is often
described as a "batteries included" language due to its comprehensive standard library.
Python was designed for readability, and has some similarities to the English language with
influence from mathematics.
Python uses new lines to complete a command, as opposed to other programming languages
which often use semicolons or parentheses.
Python relies on indentation, using whitespace, to define scope; such as the scope of loops,
functions and classes. Other programming languages often use curly-brackets for this purpose.
Indentation
Python uses whitespace indentation, rather than curly brackets or keywords, to delimit blocks. An
increase in indentation comes after certain statements; a decrease in indentation signifies the end of the
current block. Thus, the program's visual structure accurately represents its semantic structure. This
feature is sometimes termed the off-side rule. Some other languages use indentation this way; but in
most, indentation has no semantic meaning. The recommended indent size is four spaces.
Dept of ECE,MIT 3
Introduction to Python Programming Language BPCLK105B/205B
Dept of ECE,MIT 4
Introduction to Python Programming Language BPCLK105B/205B
Arithmetic operators
Assignment operators
Dept of ECE,MIT 5
Introduction to Python Programming Language BPCLK105B/205B
Comparison operators
Logical operators
Identity operators
Membership operators
Dept of ECE,MIT 6
Introduction to Python Programming Language BPCLK105B/205B
Bitwise operators
There are different types of data types in Python. Some built-in Python data types are:
Dept of ECE,MIT 7
Introduction to Python Programming Language BPCLK105B/205B
Applications
*****************
Dept of ECE,MIT 8
Introduction to Python Programming Language BPCLK105B/205B
PROGRAMS
1. a. Develop a program to read the student details like Name, USN, and Marks in three subjects.
Display the student details, total marks and percentage with suitable messages.
Out put:
enter the student name
AAA
enter your USN
4MN22ECXXX
enter your physics marks
90
enter your chemistry marks
95
enter your maths marks
89
The student details are
student name is AAA
student USN is 4MN22ECXXX
physics marks is 90
chemistry marks is 95
maths marks is 89
the total marks obtained is 274
the percentage obtained is 91.33
ALL THE BEST
*****************
Dept of ECE,MIT 9
Introduction to Python Programming Language BPCLK105B/205B
b. Develop a program to read the name and year of birth of a person. Display whether the
person is a senior citizen or not.
Output:
Enter your name
hamza
Enter your year of birth
1979
Enter present year
2023
You are not a senior citizen
*****************
Dept of ECE,MIT
10
Introduction to Python Programming Language BPCLK105B/205B
2. a. Develop a program to generate Fibonacci sequence of length (N). Read N from the console.
Output:
*****************
Dept of ECE,MIT
11
Introduction to Python Programming Language BPCLK105B/205B
def fact(num)
fact=1
for i in range (num,0,-1):
fact=fact*i
return fact
N=int (input(“Enter the value for N”))
R=int (input(“Enter the value for R”))
NF=fact(N)
RF=fact(R)
print(“Factorial of “+N+”is”, NF)
NRF=fact(N-R)
BMC=NF/(RF*(NRF))
print (“Binomial co efficient is”, BMC)
Output:
*****************
Dept of ECE,MIT
12
Introduction to Python Programming Language BPCLK105B/205B
3. Read N numbers from the console and create a list. Develop a program to print mean,
variance and standard deviation with suitable messages.
import math
def mean(data):
n=len(data)
mean=sum(data)/n
return mean
def variance(data):
n=len(data)
mean=sum(data)/n
deviation=((x-mean)**2 for x in data)
variance =sum(deviation)/n
return variance
def stddev(data):
var=variance(data)
stddev=math.sqrt(var)
return stddev
n=[]
while True:
print("to stop press -1\t"+"enter the number"+"str(len(n))"+"is")
num=int(input())
if num==-1:
break
n=n+[num]
print(n)
print("mean",mean(n))
print("variance",variance(n))
print("stddev",stddev(n))
Out put:
to stop press -1 enter the number str(len(n))is
30
to stop press -1 enter the number str(len(n))is
2
to stop press -1 enter the number str(len(n))is
5
to stop press -1 enter the number str(len(n))is
-1
[30, 2, 5]
mean 12.333333333333334
variance 157.55555555555551
stddev 12.552113589175152
*****************
Dept of ECE,MIT
13
Introduction to Python Programming Language BPCLK105B/205B
4. Read a multi-digit number (as chars) from the console. Develop a program to print the
frequency of each digit with suitable message.
*****************
Dept of ECE,MIT
14
Introduction to Python Programming Language BPCLK105B/205B
5. Develop a program to print 10 most frequently appearing words in a text file. [Hint: Use
dictionary with distinct words and their frequency of occurrences. Sort the dictionary in the
reverse order of frequency and display dictionary slice of first 10 items]
myfile=open("C:\\Users\\STUDENT\\Desktop\\python.txt",'r')
c=myfile.read()
myfile.close()
type(c)
c1=c.split()
freq={}
for c1 in c1:
if c1 in freq:
freq[c1]=freq[c1]+1
else:
freq[c1]=1
f1={}
print("frequency of words of 10 most repeating words")
for n,f in freq.items():
f1[n]=f
fsorted=sorted(f1.items(),key=lambda x:x[1])
fsorted.reverse()
fn=fsorted[0:10]
import pprint
print(pprint.pprint(fn))
Output:
frequency of words of 10 most repeating words
[('is', 5),
('name', 3),
('branch', 2),
('your', 2),
('my', 2),
('you.', 1),
('meet', 1),
('to', 1),
('nice', 1),
('sam:Ok', 1)]
*****************
Dept of ECE,MIT
15
Introduction to Python Programming Language BPCLK105B/205B
6. Develop a program to sort the contents of a text file and write the sorted contents into a
separate textfile. [Hint: Use string methods strip(), len(), list methods sort(), append(), and file
methods open(), readlines(), and write()].
file=open("C:\\Users\\STUDENT\\Desktop\\py.v.txt")
s=file.read()
file.close()
split_file=s.split()
sorted_f=sorted(split_file)
file2=open("C:\\Users\\STUDENT\\Desktop\\sortnew.txt",'w')
for x in sorted_f:
file2.write(f'{x}\n')
print('done')
file2.close()
Output:
Done
*****************
Dept of ECE,MIT
16
Introduction to Python Programming Language BPCLK105B/205B
7. Develop a program to backing up a given Folder (Folder in a current working directory) into
a ZIP File by using relevant modules and suitable methods.
import zipfile
file=zipfile.ZipFile('new.zip','w')
file.write("C:\\Users\\Student\\Desktop\\python.txt",compress_type=zipfile.ZIP_DEFLATED)
print("done")
file.close()
file=zipfile.ZipFile('new.zip')
print(file.namelist())
file.extractall('D:\\')
file.close()
Output:
done
['Users/Student/Desktop/python.txt/']
*****************
Dept of ECE,MIT
17
Introduction to Python Programming Language BPCLK105B/205B
8. Write a function named DivExp which takes TWO parameters a, b and returns a value c
(c=a/b). Write suitable assertion for a>0 in function DivExp and raise an exception for when
b=0. Develop a suitable program which reads two values from the console and calls a function
DivExp.
def DivExp(a,p):
assert a>0, “the a is less than 0”
if b==0:
raise Exception('b should not be equal to 0')
c=a/b
return c
try:
print("enter the a value")
a=int(input())
print ('enter the b values')
b=int(input())
print(DivExp(a,b))
except Exception as err:
print(err)
Output:
enter the a value
1
enter the b values
0
*****************
Dept of ECE,MIT
18
Introduction to Python Programming Language BPCLK105B/205B
9. Define a function which takes TWO objects representing complex numbers and returns new
complex number with a addition of two complex numbers. Define a suitable class ‘Complex’ to
represent the complex number. Develop a program to read N (N >=2) complex numbers and to
compute the addition of N complex numbers.
class Complex:
def __init__(self,tempReal,tempImaginary):
self.real=tempReal;
self.imaginary=tempImaginary;
def addComp(self,c1,c2):
temp=Complex(0,0)
temp.real=c1.real+c2.real;
temp.imaginary=c1.imaginary+c2.imaginary;
return temp;
if __name__=='__main__':
print("enter the complex number 1 real and imaginary part")
a=int(input())
b=int(input())
c1=Complex(a,b);
print("Complex number 1:",c1.real,"+i"+str(c1.imaginary))
print("\nenter the complex number 2real and imaginary")
c=int(input())
d=int(input())
c2=Complex(c,d);
print("Complex number 2:",c2.real,"+i"+str(c2.imaginary))
c3=Complex(0,0)
c3=c3.addComp(c1,c2);
print("\nSum of complex number:",c3.real,"+i"+str(c3.imaginary))
Output:
enter the complex number 1 real and imaginary part
33
44
Complex number 1: 33 +i44
enter the complex number 2real and imaginary
22
45
Complex number 2: 22 +i45
Sum of complex number: 55 +i89
*****************
Dept of ECE,MIT
19
Introduction to Python Programming Language BPCLK105B/205B
10. Develop a program that uses class Student which prompts the user to enter marks in three
subjects and calculates total marks, percentage and displays the score card details. [Hint: Use list
to store the marks in three subjects and total marks. Use __init__() method to initialize name,
USN and the lists to store marks and total, Use getMarks() method to read marks into the list,
and display() method to display the score card details.]
class student:
name=''
USN=''
lst=[]
def __init__(self,lst,name,USN):
self.name=name
self.marks=lst
self.USN=USN
def getMarks(self):
for x in range(3):
m=int(input('enter the marks:'))
self.lst.append(m)
def display(self):
print(\n'student name:',self.name)
print('student USN:',self.USN)
for x in range(0,3):
print(f'marks in sub{x+1}:{self.lst[x]}')
def totalmarks(self):
self.totalM=sum(self.lst)
self.perc=(self.totalM/300)*100
print('total marks=',self.totalM)
print('percentage obtained=',self.perc)
n=input('enter the name of the student\n')
usn=input('enter the student usn\n')
p=student([],n,usn)
p.getMarks()
p.display()
p.totalmarks()
Output:
enter the name of the student
AAA
enter the student usn
4MN22ECXXX
enter the marks:99
enter the marks:99
enter the marks:99
student name: AAA
student USN: 4MN22ECXXX
marks in sub1:99
marks in sub2:99
marks in sub3:99
total marks= 297
percentage obtained= 99.0
*****************
Dept of ECE,MIT
20