Introduction to Python programming Lab Manual 2023-24
INFORMATION SCIENCE AND ENGINEERING
DEPARTMENT
Introduction to Python Programming
BPLCK105B
2nd Semester CBCS 2022 Scheme
Prepared by: Prof. Shivarajkumar Hiremath
Introduction to Python programming Lab Manual 2023-24
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.
stName = input("Enter the name of the student : ")
stUSN = input("Enter the USN of the student : ")
stMarks1 = int(input("Enter marks in Subject 1 : "))
stMarks2 = int(input("Enter marks in Subject 2 : "))
stMarks3 = int(input("Enter marks in Subject 3 : "))
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))
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.
from datetime import date
perName = input("Enter the name of the person : ")
perDOB = int(input("Enter his year of birth : "))
curYear = [Link]().year
perAge = curYear - perDOB
if (perAge > 60):
print(perName, "aged", perAge, "years is a Senior Citizen.")
else:
print(perName, "aged", perAge, "years is not a Senior Citizen.")
Introduction to Python programming Lab Manual 2023-24
2 a) Develop a program to generate Fibonacci sequence of length (N). Read N from the console.
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
print()
2 b) Write a function to calculate factorial of a number. Develop a program to compute binomial
coefficient (Given N and R).
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="")
Introduction to Python programming Lab Manual 2023-24
3) Read N numbers from the console and create a list. Develop a program to print mean, variance and
standard deviation with suitable messages.
from math import sqrt
myList = []
num = int(input("Enter the number of elements in your list : "))
for i in range(num):
val = int(input("Enter the element : "))
[Link](val)
print(’The length of list1 is’, len(myList))
print(’List Contents’, myList)
total = 0
for elem in myList:
total += elem
mean = total / num
total = 0
for elem in myList:
total += (elem - mean) * (elem - mean)
variance = total / num
stdDev = sqrt(variance)
print("Mean =", mean)
print("Variance =", variance)
print("Standard Deviation =", "%.2f"%stdDev)
Introduction to Python programming Lab Manual 2023-24
4. Read a multi-digit number (as chars) from the console. Develop a program to print the frequency of
each digit with suitable message.
num = input("Enter a number : ")
print("The number entered is :", num)
uniqDig = set(num)
for elem in uniqDig:
print(elem, "occurs", [Link](elem), "times")
Introduction to Python programming Lab Manual 2023-24
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 [Link]
fname = input("Enter the filename : ") #sample file [Link] also provided
if not [Link](fname):
print("File", fname, "doesn’t exists")
[Link](0)
infile = open(fname, "r")
filecontents = ""
for line in infile:
for ch in line:
if ch not in [Link]:
filecontents = filecontents + ch
else:
filecontents = filecontents + ’ ’ #replace punctuations and \n with space
wordFreq = {}
wordList = [Link]()
#Calculate word Frequency
for word in wordList:
if word not in [Link]():
wordFreq[word] = 1
else:
wordFreq[word] += 1
Introduction to Python programming Lab Manual 2023-24
#Sort Dictionary based on values in descending order
sortedWordFreq = sorted([Link](), 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")
Introduction to Python programming Lab Manual 2023-24
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 [Link]
import sys
fname = input("Enter the filename whose contents are to be sorted : ")
if not [Link](fname):
print("File", fname, "doesn’t exists")
[Link](0)
infile = open(fname, "r")
myList = [Link]()
# print(myList)
#Remove trailing \n characters
lineList = []
for line in myList:
[Link]([Link]())
[Link]()
#Write sorted contents to new file [Link]
outfile = open("[Link]","w")
for line in lineList:
[Link](line + "\n")
[Link]() # Close the input file
[Link]() # Close the output file
if [Link]("[Link]"):
print("\nFile containing sorted content [Link] created successfully")
print("[Link] contains", len(lineList), "lines")
print("Contents of [Link]")
print("=================================================================")
rdFile = open("[Link]","r")
for line in rdFile:
print(line, end="")
Introduction to Python programming Lab Manual 2023-24
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 sys
import pathlib
import zipfile
dirName = input("Enter Directory name that you want to backup : ")
if not [Link](dirName):
print("Directory", dirName, "doesn’t exists")
[Link](0)
curDirectory = [Link](dirName)
with [Link]("[Link]", mode="w") as archive:
for file_path in [Link]("*"):
[Link](file_path, arcname=file_path.relative_to(curDirectory))
if [Link]("[Link]"):
print("Archive", "[Link]", "created successfully")
else:
print("Error in creating zip archive")
Introduction to Python programming Lab Manual 2023-24
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")
[Link](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)
Introduction to Python programming Lab Manual 2023-24
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.
class Complex:
def __init__(self, realp = 0, imagp=0):
[Link] = realp
[Link] = imagp
def setComplex(self, realp, imagp):
[Link] = realp
[Link] = imagp
def readComplex(self):
[Link] = int(input("Enter the real part : "))
[Link] = int(input("Enter the real part : "))
def showComplex(self):
print(’(’,[Link],’)’,’+i’,’(’,[Link],’)’,sep="")
def addComplex(self, c2):
c3 = Complex()
[Link] = [Link] + [Link]
[Link] = [Link] + [Link]
return c3
def add2Complex(a,b):
c = [Link](b)
return c
def main():
c1 = Complex(3,5)
c2 = Complex(6,4)
Introduction to Python programming Lab Manual 2023-24
print("Complex Number 1")
[Link]()
print("Complex Number 2")
[Link]()
c3 = add2Complex(c1, c2)
print("Sum of two Complex Numbers")
[Link]()
#Addition of N (N >=2) complex numbers
compList = []
num = int(input("\nEnter the value for N : "))
for i in range(num):
print("Object", i+1)
obj = Complex()
[Link]()
[Link](obj)
print("\nEntered Complex numbers are : ")
for obj in compList:
[Link]()
sumObj = Complex()
for obj in compList:
sumObj = add2Complex(sumObj, obj)
print("\nSum of N complex numbers is", end = " ")
[Link]()
main()
Introduction to Python programming Lab Manual 2023-24
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.]
class Student:
def __init__(self, name = "", usn = "", score = [0,0,0,0]):
[Link] = name
[Link] = usn
[Link] = score
def getMarks(self):
[Link] = input("Enter student Name : ")
[Link] = input("Enter student USN : ")
[Link][0] = int(input("Enter marks in Subject 1 : "))
[Link][1] = int(input("Enter marks in Subject 2 : "))
[Link][2] = int(input("Enter marks in Subject 3 : "))
[Link][3] = [Link][0] + [Link][1] + [Link][2]
def display(self):
percentage = [Link][3]/3
spcstr = "=" * 81
print(spcstr)
print("SCORE CARD DETAILS".center(81))
print("%15s"%("NAME"), "%12s"%("USN"), "%8s"%"MARKS1","%8s"%"MARKS2","%8s"%"
MARKS3","%8s"%"TOTAL","%12s"%("PERCENTAGE"))
print(spcstr)
print("%15s"%[Link], "%12s"%[Link], "%8d"%[Link][0],"%8d"%self.
score[1],"%8d"%[Link][2],"%8d"%[Link][3],"%12.2f"%percentage)
print(spcstr)
def main():
s1 = Student()
[Link]()
[Link]()
main()