Python Lab Manual 1st Year
Python Lab Manual 1st Year
ENGINEERING
2024-2025
Total Hours of Pedagogy 40 hours Theory + 8-10 Lab slots Total Marks 100
Sl. No Experiments
a.Develop a program to read the student details like Name, USN, and Marks in three
1
subjects Display the student details, total marks and percentage with suitable
messages.
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.
a. Develop a program to generate Fibonacci sequence of length (N). Read N from the
2
console.
b. Write a function to calculate factorial of a number. Develop a program to compute
binomial coefficient (Given N and R).
Read N numbers from the console and create a list. Develop a program to print mean,
3
variance and standard deviation with suitable messages.
Read a multi-digit number (as chars) from the console. Develop a program to print
4
the frequency of each digit with suitable message.
Develop a program to rint 10 most frequently appearing words in a text file. [Hint:
5
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].
Develop a program to sort the contents of a text file and write the sorted contents into
6
a separate text file. [Hint: Use string methods strip (), len (), list methods sort(),
append(), and file methods open(), readlines(), and write()].
Write a function named DivExp which takes TWO parameters a, b and returns a value
8
c (c=a/b). Write suitable assertion for a>0 in function DivExp and raise an exception
Dept Of CS&E,AIT P a g e 2 | 17
Python Lab Manual BIPPB105/205
for when b=0. Develop a suitable program which reads two values from the console and
calls a function DivExp.
Define a function which takes TWO objects representing complex numbers and
9
returns new complex number with an 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.
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 get
Marks() method to read marks into the list, and display() method to display the score
card details.
Dept Of CS&E,AIT P a g e 3 | 17
Python Lab Manual BIPPB105/205
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:
Dept Of CS&E,AIT P a g e 4 | 17
Python Lab Manual BIPPB105/205
1.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
Dept Of CS&E,AIT P a g e 5 | 17
Python Lab Manual BIPPB105/205
2. a. Develop a program to generate Fibonacci sequence of length (N). Read N from the console.
Output:
Dept Of CS&E,AIT P a g e 6 | 17
Python Lab Manual BIPPB105/205
Output:
Dept Of CS&E,AIT P a g e 7 | 17
Python Lab Manual BIPPB105/205
3. Read N numbers from the console and create a list. Develop a program to print mean,
variance and standard deviation with suitable messages.
Output:
Dept Of CS&E,AIT P a g e 8 | 17
Python Lab Manual BIPPB105/205
4. Read a multi-digit number (as chars) from the console. Develop a program to print the
frequency of each digit with suitable message.
Output:
Dept Of CS&E,AIT P a g e 9 | 17
Python Lab Manual BIPPB105/205
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 sys
import string
import os.path
fname = input("Enter the filename : ")
#sample file text.txt is given
if not os.path.isfile(fname):
print("File", fname, "doesn’t exists")
sys.exit(0)
infile = open(fname, "r")
filecontents = ""
for line in infile:
for ch in line:
if ch not in string.punctuation:
filecontents = filecontents +
else:
filecontents = filecontents + ' '#replace punctuations and \n with space
wordFreq = {}
wordList = filecontents.split()
#Calculate word Frequency
for word in wordList:
if word not in wordFreq.keys():
wordFreq[word] = 1
else:
wordFreq[word] += 1
#Sort Dictionary based on values in descending order
sortedWordFreq = sorted(wordFreq.items(), key=lambda x:x[1], reverse=True )
#Display 10 most frequently appearing words with their count
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:
Dept Of CS&E,AIT P a g e 10 | 17
Python Lab Manual BIPPB105/205
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()].
import os
import sys
# Get the filename from the user
fname = input("Enter the filename whose contents are to be sorted: ") # sample file Text.txt
# Check if the file exists
if not os.path.isfile(fname):
print("File", fname, "doesn't exist")
sys.exit(0)
# Read the contents of the file
with open(fname, "r") as infile:
myList = infile.readlines()
# Remove trailing newline characters and create a sorted list
lineList = [line.strip() for line in myList]
lineList.sort() # Sort the list
# Write sorted contents to a new file sorted.txt
with open("sorted.txt", "w") as outfile:
for line in lineList:
outfile.write(line + "\n")
# Check if sorted.txt was created and display its contents
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("==========================================================")
Output:
Dept Of CS&E,AIT P a g e 11 | 17
Python Lab Manual BIPPB105/205
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 os
import sys
import pathlib
import zipfile
dirName = input("Enter Directory name that you want to backup: ")
if not os.path.isdir(dirName):
print("Directory", dirName, "doesn’t exist")
sys.exit(0)
curDirectory = pathlib.Path(dirName)
with zipfile.ZipFile("myZip.zip", mode="w") as archive:
for file_path in curDirectory.rglob("*"):
archive.write(file_path, arcname=file_path.relative_to(curDirectory))
if os.path.isfile("myZip.zip"):
print("Archive", "myZip.zip", "created successfully")
else:
print("Error in creating zip archive")
Output:
Dept Of CS&E,AIT P a g e 12 | 17
Python Lab Manual BIPPB105/205
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.
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
val1 = int(input("Enter a value for a: "))
val2 = int(input("Enter a value for b: "))
val3 = DivExp(val1, val2)
print(val1, "/", val2, "=", val3)
Output:
Dept Of CS&E,AIT P a g e 13 | 17
Python Lab Manual BIPPB105/205
9. Define a function which takes TWO objects representing complex numbers and returns new
complex number with an 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, realp=0, imagp=0):
self.realp = realp
self.imagp = imagp
def setComplex(self, realp, imagp):
self.realp = realp
self.imagp = imagp
def readComplex(self):
self.realp = int(input("Enter the real part: "))
self.imagp = int(input("Enter the imaginary part: ")) # Fixed prompt text
def showComplex(self):
print('(', self.realp, ') + i(', self.imagp, ')', sep="") # Fixed quotes
def addComplex(self, c2):
c3 = Complex()
c3.realp = self.realp + c2.realp
c3.imagp = self.imagp + c2.imagp
return c3
def add2Complex(a, b):
return a.addComplex(b)
def main():
# Create two complex numbers using the constructor
c1 = Complex(3, 5)
c2 = Complex(6, 4)
print("Complex Number 1:")
c1.showComplex()
for i in range(num):
print("Object", i + 1)
obj = Complex()
obj.readComplex()
compList.append(obj)
print("\nEntered Complex numbers are:")
for obj in compList:
obj.showComplex()
sumObj = Complex()
for obj in compList:
sumObj = add2Complex(sumObj, obj)
print("\nSum of N complex numbers is:", end=" ")
sumObj.showComplex()
# Entry point of the program
if __name__ == "__main__":
main()
Dept Of CS&E,AIT P a g e 14 | 17
Python Lab Manual BIPPB105/205
Output:
Dept Of CS&E,AIT P a g e 15 | 17
Python Lab Manual BIPPB105/205
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 get Marks() method to read marks into the list,
and display() method to display the score card details.
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 %12s %8s %8s %8s %8s %12s" % ("NAME", "USN", "MARKS1", "MARKS2",
"MARKS3", "TOTAL", "PERCENTAGE"))
print(spcstr)
print("%15s %12s %8d %8d %8d %8d %12.2f" % (self.name, self.usn, self.score[0], self.score[1],
self.score[2], self.score[3], percentage))
print(spcstr)
def main():
s1 = Student()
s1.getMarks()
s1.display()
if __name__ == "__main__":
main()
Dept Of CS&E,AIT P a g e 16 | 17
Python Lab Manual BIPPB105/205
Output:
Dept Of CS&E,AIT P a g e 17 | 17