Python Lab Manual
Python Lab Manual
Program 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.
Program
Name=input("enter the student name")
Usn=input("enter the student USN")
Subject1_marks=int(input("enter the subject one marks"))
Subject2_marks=int(input("enter the subject two marks"))
Subject3_marks=int(input("enter the subject three marks"))
Total_marks=Subject1_marks+Subject2_marks+Subject3_marks
Percentage=((Subject1_marks+Subject2_marks+Subject3_marks)/300)*100
print("student bearing Usn "+Usn+" and name "+ Name+" has scored a total marks
"+str(Total_marks)+" and percentage is "+str(Percentage))
Output.
enter the student name Ananya
enter the student USN 4PM12CS02
enter the subject one marks 56
enter the subject two marks 78
enter the subject three marks 89
student bearing Usn 4PM12CS02 and name Ananya has scored a total marks 223 and
percentage is 74.33333333333333
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.
Program.
Name=input("Enter your name")
Year_of_Birth=int(input("Enter your year of birth"))
Current_year=2023
age=Current_year-Year_of_Birth
if age>=60:
print('senior citizen')
else:
print('not a senior citizen')
Output.
Enter your name Aman
Enter your year of birth 1967
not a senior citizen
Program 2
a. Develop a program to generate Fibonacci sequence of length (N). Read N from the console.
Code:
def fib(nterms):
n1, n2 = 0, 1
count = 0
if nterms <= 0:
print("Please enter a positive integer")
else:
print("Fibonacci sequence for number "+str(nterms)+" is")
while count < nterms:
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
number = int(input("How many terms? "))
fib(number)
Output:
How many terms? 5
Fibonacci sequence for number 5 is
0
1
1
2
3
b)Write a function to calculate factorial of a number. Develop a program to compute
binomial coefficient (Given N and R).
Code:
def factorial(z):
if z==1:
return 1
else:
return z* factorial(z-1)
def binomial_coefficient(n,k):
a= (factorial(n) / factorial(k) * factorial(n-k))
return a
n=int(input("enter a number to find factorial"))
print("The factorial of number "+str(n) +"is",factorial(n))
k=int(input("enter the number to find binomial coefficient"))
print("The binomial coefficient is:",binomial_coefficient(n,k))
Output
enter a number to find factorial4
The factorial of number 4is 24
enter the number to find binomial coefficient2
The binomial coefficient is: 6.0
Program 3:
Read N numbers from the console and create a list. Develop a program to
print mean, variance and standard deviation with suitable messages.
Code:
import math
data=[1,4,3,5,6]
def mean(data):
n=len(data)
mean=sum(data)/n
return mean
print(“the mean is" + str (mean(data)))
def variance(data):
n=len(data)
mean=sum(data)/n
dev=[(x-mean)**2 for x in data]
var=sum(dev)/n
return var
print("the variance is "+str(variance(data)))
def standardDev(data):
var=variance(data)
std=math.sqrt(var)
return std
print("the standard deviation is "+str(standardDev(data)))
Output:
the mean is 3.8
the variance is 2.96
the standard deviation is 1.7204650534085253
Program 4:
Read a multi-digit number (as chars) from the console. Develop a program
to print the frequency of each digit with suitable message.
Code:
num=input('Enter a multidigit number: ')
d={}
for i in num:
d.setdefault(i,0)
d[i]=d[i]+1
print(d)
for i in d:
print('Frequency of '+str(i)+' is '+str(d[i]))
Output:
Enter a multidigit number: 12342312445788
{'1': 2, '2': 3, '3': 2, '4': 3, '5': 1, '7': 1, '8': 2}
Frequency of 1 is 2
Frequency of 2 is 3
Frequency of 3 is 2
Frequency of 4 is 3
Frequency of 5 is 1
Frequency of 7 is 1
Frequency of 8 is 2
Program 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]
Code:
import itertools
text=open('C:\\Users\\PC\\AppData\\Local\\Programs\\Python\\Python311\\file.txt')
d={}
for line in text.readlines(): #line is a string
line = line.strip()
line = line.lower()
words = line.split(" ") #words is a list
for i in words:
d.setdefault(i,0)
d[i]=d[i]+1
print('Frequency of each word in a text file: \n',d)
sort=dict(sorted(d.items(),key=lambda x:x[1],reverse=True))
print('\nSorted dictionary in reverse order: \n',sort)
out = dict(itertools.islice(sort.items(), 10))
print('\n10 Most frequently appearing words in a text file: \n',out)
text.close()
Output:
Sorted dictionary in reverse order:
{'the': 9, 'if': 4, 'on': 3, 'breakpoint': 2, 'statement': 2, 'you': 1, 'don’t': 1, 'want': 1, 'to': 1,
'set': 1, 'a': 1, 'line,': 1, 'since': 1, 'is': 1, 'executed': 1, 'every': 1, 'single': 1, 'iteration': 1,
'through': 1, 'loop.': 1, 'by': 1, 'setting': 1, 'code': 1, 'in': 1, 'statement,': 1, 'debugger': 1, 'breaks':
1, 'only': 1, 'when': 1, 'execution': 1, 'enters': 1, 'clause.': 1}
10 Most frequently appearing words in a text file:
{'the': 9, 'if': 4, 'on': 3, 'breakpoint': 2, 'statement': 2, 'you': 1, 'don’t': 1, 'want': 1, 'to': 1,
'set': 1}
Program 6:
Develop a program to sort the contents of a text file and write the sorted
contents into a separate text file. [Hint: Use string methods strip(), len(), list methods
sort(), append(), and file methods open(), readlines(), and write()].
Code:
list1=[]
file=open("D:\\hello1.txt")
var=file.readlines()
print(var)
for i in var:
list1.append(i.strip())
print(list1)
list1.sort()
print(list1)
file.close()
file1=open("D:\\hello2.txt",'w')
for i in list1:
file1.write(i+'\n')
file1.close()
Output:
['vidya\n', 'anugna\n', 'shruthi\n', 'bindu\n']
Hello1.txt:['vidya', 'anugna', 'shruthi', 'bindu']
Hello2.txt:['anugna', 'bindu', 'shruthi', 'vidya']
Program 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.
Code:
import zipfile, os
def backupToZip(folder):
folder = os.path.abspath(folder) # make sure folder is absolute
number = 1
while True:
zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
if not os.path.exists(zipFilename):
break
number = number + 1
print('Creating %s...' % (zipFilename))
backupZip = zipfile.ZipFile(zipFilename, 'w')
for foldername, subfolders, filenames in os.walk(folder):
print('Adding files in %s...' % (foldername))
backupZip.write(foldername)
for filename in filenames:
if filename.startswith(os.path.basename(folder) + '_') and
filename.endswith('.zip'):
continue
backupZip.write(os.path.join(foldername, filename))
backupZip.close()
print('Done.')
backupToZip('C:\\Users\\PC\\AppData\\Local\\Programs\\Python\\Python311\\PES')
Output:
Creating PES_1.zip...
Adding files in C:\Users\PC\AppData\Local\Programs\Python\Python311\PES...
Adding files in C:\Users\PC\AppData\Local\Programs\Python\Python311\PES\pes1...
Done.
Program 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
Code:
def DivExp(a,b):
assert a>0,"a is greater than zero"
if b==0:
raise Exception("value of b cannot be zero")
else:
c=a/b
return c
a=int(input("enter the value of A"))
b=int(input("enter the value of B"))
try:
print(DivExp(a,b))
except Exception as err:
print(err)
Output:
Output1:
enter the value of A4
enter the value of B0
value of b cannot be zero
Output2:
enter the value of A0
enter the value of B4
a is greater than zero
Program 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.
Code:
class Complex:
def __init__(self, real=0,img=0):
self.real=real
self.img=img
def __add__(self,other):
out=Complex()
out.real=self.real+other.real
out.img=self.img+other.img
return out
def __str__(self):
return '%.2d+%.2d j' % (self.real,self.img)
N=int(input('Enter the number of complex numbers:'))
a=[ ]
for i in range(0,N):
real=int(input('Enter the real part of complex number '+str(i)+': '))
img=int(input('Enter the imaginary part of complex number '+str(i)+': '))
a.append(Complex(real,img))
if N%2!=0:
a.append(Complex(0,0))
res=Complex()
for i in range(0,N,2):
temp=a[i]+a[i+1]
res+=temp
print(res)
Output:
Enter the number of complex numbers:4
Enter the real part of complex number 0: 1
Enter the imaginary part of complex number 0: 3
Enter the real part of complex number 1: 1
Enter the imaginary part of complex number 1: 3
Enter the real part of complex number 2: 1
Enter the imaginary part of complex number 2: 3
Enter the real part of complex number 3: 1
Enter the imaginary part of complex number 3: 3
04+12 j
OR
Code:
class Complex:
'''
creats objects of complex type
'''
def sum(a,b):
c=Complex()
c.real=a.real+b.real
c.img=a.img+b.img
return c
a=Complex()
a.real=int(input('Enter the real part of a: '))
a.img=int(input('Enter the img part of a: '))
b=Complex()
b.real=int(input('Enter the real part of b: '))
b.img=int(input('Enter the img part of b: '))
c=sum(a,b)
print(c.real,'+',c.img,'j')
Output:
Enter the real part of a:2
Enter the img part of a:3
Enter the real part of b:4
Enter the img part of b:5
6+9j
Program 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.]
Code:
class Student:
def __init__(self):
self.name=input('Enter the student name: ')
self.usn=input('Enter the student USN: ')
self.marks =[]
def getMarks(self):
total = 0
for i in range(3):
self.marks.append(int(input('Enter the marks of subject '+str(i+1)+': ')))
total+=self.marks[i]
self.marks.append(total)
def Display(self):
print('------------**********-------------',end='\n\n')
print('Student\'s score card: ')
print('Student name:', self.name)
print('Student USN:', self.usn)
for i in range(3):
print('subject '+str(i+1)+' marks:',self.marks[i])
print ('Total marks: ',self.marks[3])
print ('Percentage: ',self.marks[3]/3)
s=Student()
s.getMarks()
s.Display()
Output:
Enter the student name: Sahana
Enter the student USN: 054
Enter the marks of subject 1: 78
Enter the marks of subject 2: 67
Enter the marks of subject 3: 57
------------**********-------------
Student's score card:
Student name: Sahana
Student USN: 054
subject 1 marks: 78
Total marks: 156
Percentage: 52.0
subject 2 marks: 78
Total marks: 156
Percentage: 52.0
subject 3 marks: 67
Total marks: 156
Percentage: 52.0