Python Lab Manual
Python Lab Manual
Python Lab Manual
TECHNOLOGY
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
INTRODUCTION TO PYTHON
PROGRAMMING (BPCLK105B)
1ST SEMESTER
LABORATORY MANUAL
Prepared By:
APPROVED BY
Name: ………..………………………………………………………………
Sl No. PARTICULARS
1 COURSE DETAILS
COURSE OBJECTIVES
SYLLABUS
COURSE OUTCOMES
2 EVALUATION PROCESS
Lab Programs:
PYTHON PROGRAMS
1(a) Develop a program to read the student details
1(b) Develop a program to read the name and year of birth of a person
2 Develop a program to generate Fibonacci sequence
3 Develop a program to print mean, variance and standard deviation
4 Develop a program to print the frequency of each digit
5 Develop a program to print 10 most frequently appearing words in a text file
6 Develop a program to sort the contents of a text file and write the sorted contents into a
separate text file
7 Develop a program to backing Up a given into a ZIP File by using relevant modules and
suitable methods.
8 Develop a suitable program which reads two values from the console and calls a function
DivExp.
9 Develop a program to read N (N >=2) complex numbers and to compute the addition of N
complex numbers.
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
PYTHON PROGRAMMING LABORATORY-BPCLK105B 2022-2023
COURSE DETAILS
Course Objectives
PYTHON 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.
Output :
(b) Develop a program to read the name and year of birth of a person. Display whether the person is a
if y >= 60:
print ( name+” is a senior citizen” )
else :
print ( name+” is not a senior citizen”
Output :
Output1:
Enter the name of the person: Rashmi
Enter the year of birth of the person: 1993
Rashmi is not a senior citizen
Output2:
Enter the name of the person: Alice
Enter the year of birth of the person: 1940
Alice is a senior citizen
( 2 ) Develop a program to generate Fibonacci sequence of length (N). Read N from the console.
fibonacci(n)
Output:
enter the value of n: 9
0 1 1 2 3 5 8 13 21 34
2 b. Write a function to calculate factorial of a number. Develop a program to compute binomial coefficient
(Given N and R).
Output:
enter the values of n: 4
enter the values of r: 2
Factorial of 4 is 24
binomial coefficient is 6.0
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(a):
sum1=0
for i in a:
sum1+=i
m=sum1/N
return m
def var(a,m):
dev = 0
for y in a:
dev+=(y-m)**2
variance = dev/N
deviation = math.sqrt(variance)
return deviation, variance
N= int(input("enter the N: "))
List =[]
for i in range(N):
x = int(input("enter the list value:"))
List.append(x)
average=mean(List)
std_dev, variance =var(List,average)
print("mean: ",average)
print("Dev: ",std_dev)
print("var:",variance)
Output:
enter the N: 3
enter the list value:5
enter the list value:6
enter the list value:7
mean: 6.0
Dev: 0.816496580927726
var: 0.6666666666666666
4. Read a multi-digit number (as chars) from the console. Develop a program to print the frequency
of each digit with suitable message.
# Open the file in read mode
text = open("sample.txt", "r")
d[word] = d[word] + 1
else:
# Add the word to dictionary with count 1
d[word] = 1
Output:
mango : 3
banana : 3
apple : 3
pear : 2
grapes : 1
strawberry : 2
kiwi : 1
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]
import operator
import itertools
import pprint
text =open(“p1.txt” , ”r”)
d = dict()
for line in text:
line = line.strip()
line = line.lower()
words = line.split(" ")
for word in words:
if word in d:
d[word] = d[word] + 1
else:
d[word] = 1
sorted_d = dict( sorted(d.items(), key=operator.itemgetter(1),reverse=True))
print('Dictionary in reverse order of frequency :')
pprint.pprint(sorted_d)
out = dict(itertools.islice(sorted_d.items(), 10))
print("'first 10 items are: ")
pprint.pprint(out)
Output :
Dictionary in reverse order of frequency :
{'alice': 6,
'apple': 9,
'bob': 6,
'c': 3,
'c++': 3,
'he': 3,
'hello': 9,
'hi': 6,
'join': 3,
'list': 3,
'pyhton': 3,
'tuple': 3,
'welcome': 6}
'first 10 items are:
{'alice': 6,
'apple': 9,
'bob': 6,
'he': 3,
'hello': 9,
'hi': 6,
'join': 3,
'list': 3,
'pyhton': 3,
'welcome': 6}
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()].
f = open("5.txt","r")
data = f.readlines()
sorted_word = []
for line in data:
line = line.strip()
line = line.lower()
words = line.split(" ")
for i in words:
sorted_word.append(i)
sorted_word.sort()
f.close()
o = open("result2.txt","w")
for i in range(len(sorted_word)):
o.write(sorted_word[i])
o.write(" ")
o.close()
Output :-
7. Develop a program to backing up a given folder(Folder in a current working directory) into a ZIP file by
using relevent modules and suitable methods
import zipfile, os
def backupToZip(folder):
number = 1
while True:
zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
if not os.path.exists(zipFilename):
break
number = number + 1
print(f'Creating {zipFilename}...')
backupZip = zipfile.ZipFile(zipFilename, 'w')
for foldername, subfolders, filenames in os.walk(folder):
print(f'Adding files in {foldername}...')
backupZip.write(foldername)
for filename in filenames:
newBase = os.path.basename(folder) + '_'
if filename.startswith(newBase) and filename.endswith('.zip'):
continue # don't back up the backup ZIP files
backupZip.write(os.path.join(foldername, filename))
backupZip.close()
print('Done.')
backupToZip('C:\\Users\\EWITISE-16\\desktop\\python')
Output:
Creating python_1.zip...
Done.
8. Write a function named DivExp which takes two parameters a, b returns 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 , b):
try:
assert a>0, "a value must be greater than 0"
if b==0:
raise Exception("cannot divide by zero")
else:
c = a/b
return c
except Exception as err:
print(err)
Output 2:
enter the value of a:0
enter the value of b:5
a value must be greater than 0
Output 3:
enter the value of a:6
enter the value of b:0
cannot divide by zero
9. Define a function which takes TWO objects representing complex numbers and returns a 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.
# Constructor to accept
# real and imaginary part
def init (self, tempReal, tempImaginary):
self.real = tempReal;
self.imaginary = tempImaginary;
# Driver code
if name ==' main ':
Output
Complex number 1 : 3 + i2
Complex number 2 : 9 + i5
Sum of complex number : 12 + i7
10. Develop a program that uses class Student which prompts the user to enter marks in three subjects
andcalculates total marks, percentage and displays the score card details. [Hint: Use list to store the marksin
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 thescore card
details.]
class Student:
def init (self,name,usn):
self.name = name
self.usn = usn
self.marklist = []
self.total_marks = 0
def getMarks(self):
print("Enter marks in 3 subjects:")
for i in range(3):
m = int(input())
self.marklist.append(m)
self.total_marks += m
def display(self):
print("Name:", self.name)
print("USN:", self.usn )
print("Marks:", self.marklist)
print("Total: " , self.total_marks)
print("Percentage: " , self.total_marks/3)
name = input("Enter your name: ")
usn = input("Enter your USN: ")
s1 = Student(name, usn)
s1.getMarks()
s1.display()
Output :
Enter your name: prath
Enter your USN: iew22ad001
Enter marks in 3 subjects:
85
86
96
Name: prath
USN: iew22ad001
Marks: [85, 86, 96]
Total: 267
Percentage: 89.0
INSTITUTE VISION
To be an Institute of Academic Excellence in Technical and Management
Education on par with Global standards to meet the changing needs of the
Society.
INSTITUTE MISSION
To impart quality technical education that nurtures the young minds by
M1
providing the best of teaching learning process and state of the art infrastructure
M2 To foster technological advancement through research
M3 To inculcate holistic personality development through best practices
To implant ethical and social commitment that grooms the students to become
M4 responsible citizens
DEPARTMENT VISION
To provide Quality Technical Education in Information Science & Engineering
with Enriched Knowledge and Research Skills to Meet the Emerging
Challenges with Ethical values
DEPARTMENT MISSION
M1 To prepare students with strong fundamental concepts, analytical capability,
programming and problem solving skills
To impart Technical knowledge inculcating real time research experience to promote
M2 industrial & societal needs
To motivate and encourage skill based activities for transforming creative ideas to real
M3
time workable products
To prepare graduates to meet carrier challenges with a blend of social, human and ethical
M4
values