Python - Lab Manual
Python - Lab Manual
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.
Python Code
print("Student Details\n=========================")
print("%12s"%("Name :"), stName)
print("%12s"%("Reg.No :"), stregno)
print("%12s"%("Marks 1 :"), stMarks1)
print("%12s"%("Marks 2 :"), stMarks2)
print("%12s"%("Marks 3 :"), stMarks3)
print("%12s"%("Total :"), stMarks1+stMarks2+stMarks3)
print("%12s"%("Percent :"), "%.2f"%((stMarks1+stMarks2+stMarks3)/3))
print("=========================")
Output
Develop a program to read the name and year of birth of a person. Display whether the
person is a senior citizen or not.
Python Code
curYear = date.today().year
perAge = curYear - perDOB
Output
Question 2
a. Fibonacci Sequence
Develop a program to generate Fibonacci sequence of length (N). Read N from the
console.
Python Code
firstTerm = 0
secondTerm = 1
print("The Fibonacci series with", num, "terms is :")
print(firstTerm, secondTerm, end=" ")
for i in range(2,num):
curTerm = firstTerm + secondTerm
print(curTerm, end=" ")
firstTerm = secondTerm
secondTerm = curTerm
Output
Python Code
def fact(num):
if num == 0:
return 1
else:
return num * fact(num-1)
print(n,'C',r," = ","%d"%nCr,sep="")
Output
Read N numbers from the console and create a list. Develop a program to print mean,
variance and standard deviation with suitable messages.
Python Code
myList = []
for i in range(num):
val = int(input("Enter the element : "))
myList.append(val)
total = 0
for elem in myList:
total += elem
total = 0
for elem in myList:
total += (elem - mean) * (elem - mean)
stdDev = sqrt(variance)
Output
Mean = 58.4
Variance = 642.64
Standard Deviation = 25.35
Question 4
Digit Frequency
Read a multi-digit number (as chars) from the console. Develop a program to print the
frequency of each digit with suitable message.
Python Code
uniqDig = set(num)
#print(uniqDig)
Output
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]
Python Code
import sys
import string
import os.path
if not os.path.isfile(fname):
print("File", fname, "doesn't exists")
sys.exit(0)
filecontents = ""
wordFreq = {}
wordList = filecontents.split()
print("\n===================================================")
print("10 most frequently appearing words with their count")
print("===================================================")
for i in range(10):
print(sortedWordFreq[i][0], "occurs", sortedWordFreq[i][1], "times")
Output
===================================================
10 most frequently appearing words with their count
===================================================
the occurs 45 times
of occurs 24 times
party occurs 12 times
part occurs 12 times
a occurs 9 times
and occurs 8 times
second occurs 7 times
to occurs 6 times
shall occurs 6 times
first occurs 5 times
Question 6
Sort File Contents
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()].
Python Code
import os.path
import sys
if not os.path.isfile(fname):
print("File", fname, "doesn't exists")
sys.exit(0)
myList = infile.readlines()
# print(myList)
lineList.sort()
outfile = open("sorted.txt","w")
if os.path.isfile("sorted.txt"):
print("\nFile containing sorted content sorted.txt created
successfully")
print("sorted.txt contains", len(lineList), "lines")
print("Contents of sorted.txt")
print("=================================================================")
rdFile = open("sorted.txt","r")
for line in rdFile:
print(line, end="")
Output
Question 7
Backup Directory into Zip archive
Python Code
import os
import sys
import pathlib
import zipfile
if not os.path.isdir(dirName):
print("Directory", dirName, "doesn't exists")
sys.exit(0)
curDirectory = pathlib.Path(dirName)
if os.path.isfile("myZip.zip"):
print("Archive", "myZip.zip", "created successfully")
else:
print("Error in creating zip archive")
Output
Question 8
Assertions and Exceptions Demo
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.
Python Code
import sys
def DivExp(a,b):
assert a>0, "a should be greater than 0"
try:
c = a/b
except ZeroDivisionError:
print("Value of b cannot be zero")
sys.exit(0)
else:
return c
Output
Question 9
Complex Class Demo
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.
Python Code
class Complex:
def init (self, realp = 0, imagp=0):
self.realp = realp
self.imagp = imagp
def readComplex(self):
self.realp = int(input("Enter the real part : "))
self.imagp = int(input("Enter the real part : "))
def showComplex(self):
print('(',self.realp,')','+i','(',self.imagp,')',sep="")
def add2Complex(a,b):
c = a.addComplex(b)
return c
def main():
c1 = Complex(3,5)
c2 = Complex(6,4)
print("Complex Number 1")
c1.showComplex()
print("Complex Number 2")
c2.showComplex()
c3 = add2Complex(c1, c2)
compList = []
for i in range(num):
print("Object", i+1)
obj = Complex()
obj.readComplex()
compList.append(obj)
sumObj = Complex()
for obj in compList:
sumObj = add2Complex(sumObj, obj)
main()
Output
Complex Number 1
(3)+i(5)
Complex Number 2
(6)+i(4)
Sum of two Complex Numbers
(9)+i(9)
Question 10
Student Class Demo
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.]
Python Code
class Student:
def init (self, name = "", usn = "", score = [0,0,0,0]):
self.name = name
self.usn = usn
self.score = score
def getMarks(self):
self.name = input("Enter student Name : ")
self.usn = input("Enter student USN : ")
self.score[0] = int(input("Enter marks in Subject 1 : "))
self.score[1] = int(input("Enter marks in Subject 2 : "))
self.score[2] = int(input("Enter marks in Subject 3 : "))
self.score[3] = self.score[0] + self.score[1] + self.score[2]
def display(self):
percentage = self.score[3]/3
spcstr = "=" * 81
print(spcstr)
print("SCORE CARD DETAILS".center(81))
print(spcstr)
print("%15s"%("NAME"), "%12s"%("USN"),
"%8s"%"MARKS1","%8s"%"MARKS2","%8s"%"MARKS3","%8s"%"TOTAL","%12s"%("PERCENT
AGE"))
print(spcstr)
print("%15s"%self.name, "%12s"%self.usn,
"%8d"%self.score[0],"%8d"%self.score[1],"%8d"%self.score[2],"%8d"%self.scor
e[3],"%12.2f"%percentage)
print(spcstr)
def main():
s1 = Student()
s1.getMarks()
s1.display()
main()
Output