Python Lab Manual
Python Lab Manual
A
Laboratory Report on
KALABURAGI
2024-2025
VISVESVARAYA TECHNOLOGICAL UNIVERSITY, BELAGAVI
CPGS, Kalaburagi
U.S.N: DATE:
CERTIFICATE
Examiners:
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
2 the console.
4 Read a multi-digit number (as chars) from the console. Develop a program to print
the frequency of each digit with suitable message.
Develop a program to print 10 most frequently appearing words in a text file.[Hint: Use
5 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
6 into 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 Div Exp which takes TWO parameters a, b and returns a value c
8 (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 Div Exp.
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
9 ‘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.
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
10 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.]
1a. 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 :
print("Student Details\n=========================")
print("%12s"%("Name :"), stName)
print("%12s"%("USN :"), stUSN)
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:
Enter the name of the student : Vivek
Enter the USN of the student : 3VY22CS005
Enter marks in Subject 1 :90
Enter marks in Subject 2 : 89
Enter marks in Subject 3 : 88 StudentDetails
=========================
Name : Vivek
USN : 3VY22CS005
Marks 1 : 90
Marks 2 : 89
Marks 3 : 88
Total : 267
Percent : 89.00
=======================
Program:
Output:
Program :
OUTPUT:
Enter the Fibonacci sequence length to be generated : 8
The Fibonacci series with 8 terms is :
0 1 1 2 3 5 8 13
def fact(num):
if num == 0:
return 1
else:
return num * fact(num-1)
n = int(input("Enter the value of N : " ))
r = int(input("Enter the value of R (R cannot be negative or greater than N):"))
nCr = fact(n)/(fact(r)*fact(n-r))
print(n,'C',r," = ","%d"%nCr,sep="")
Output:
Program :
Output :
Program :
OUTPUT
Program :
import sys
import string
import os.path
fname = input("Enter the filename : ")
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 + ch
else:
filecontents = filecontents + ' '
wordFreq = {}
wordList = filecontents.split()
for word in wordList:
if word not in wordFreq.keys():
wordFreq[word] = 1
else:
wordFreq[word] += 1
sortedWordFreq = sorted(wordFreq.items(), key=lambda x:x[1], reverse=True )
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
Program :
import os.path
import sys
fname = input("Enter the filename whose contents are to be sorted : ")
if not os.path.isfile(fname):
print("File", fname, "doesn't exists")
sys.exit(0)
infile = open(fname, "r")
myList = infile.readlines()
lineList = []
for line in myList:
lineList.append(line.strip())
lineList.sort()
outfile = open("sorted.txt","w")
for line in lineList:
outfile.write(line + "\n")
infile.close()
outfile.close()
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:
Program :
import os
import zipfile
# Example usage
folder_to_backup = 'your_folder_name' # Replace with your folder name
zip_file_name = 'backup.zip' # Replace with your desired zip file name
backup_folder_to_zip(folder_to_backup, zip_file_name)
Output:
Backup completed:
C:\Users\krcom\AppData\Local\Programs\Python\Python312\backup.zip
Program :
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:
Program :
class Complex:
def init (self, real, imag):
self.real=real
self.imag=imag
def add_complex(c1,c2):
real_part = c1.real + c2.real
imag_part = c1.imag + c2.imag
return Complex(real_part,imag_part)
c1 = Complex(2, 3)
c2 = Complex(4, 5)
result = add_complex(c1,c2)
print("sum of", c1.real, "+", c1.imag, "i and", c2.real, "+", c2.imag, "i is:", result.real, "+",
result.imag, "i")
OUTPUT :
sum of 2 + 3 i and 4 + 5 i is: 6 + 8
Program :
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"%("PERCE
NTAGE"))
print(spcstr)
print("%15s"%self.name, "%12s"%self.usn,
"%8d"%self.score[0],"%8d"%self.score[1],"%8d"%self.score[2],"%8d"%self.score[3],"%12.2f"%per
centage)
print(spcstr)
def main():
s1 = Student()
s1.getMarks()
s1.display()
main()
========================================================================
SCORE CARD DETAILS
========================================================================
NAME USN MARKS1 MARKS2 MARKS3 TOTAL PERCENTAGE
===============================================================================
SUHANA 3VYCS001 45 68 90 203 67.67
===============================================================================