Lab Programs
BPLCK205B Introduction to Python Programming
Second Semester, 2022-23
Dr Loganathan R
Professor & HOD
Department of Information Science and Engineering
Sri Venkateshwara College of Engineering, Bengaluru
Programming Exercises
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.
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.
2. a. Develop a program to generate Fibonacci sequence of length (N). Read N from the console.
b. Write a function to calculate factorial of a number. Develop a program to compute binomial coefficient
(Given N and R).
3. Read N numbers from the console and create a list. Develop a program to print mean, variance and
standard deviation with suitable messages.
4. Read a multi-digit number (as chars) from the console. Develop a program to print the frequency of
each digit with suitable message.
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]
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()].
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.
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.
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.
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.]
Solutions:
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:
# Read student details
name = input("Enter student name: ")
usn = input("Enter student USN: ")
m1 = int(input("Enter Subject 1 Marks: "))
m2 = int(input("Enter Subject 2 Marks: "))
m3 = int(input("Enter Subject 3 Marks: "))
# Calculate total marks and percentage
totMarks = m1 + m2 + m3
percentage = totMarks / 3
print("Student Details:")
print("Name:", name)
print("USN:", usn)
print("Marks:", m1,m2,m3)
print("Total Marks:", totMarks)
print("Percentage:", percentage, "%")
Ouput:
Enter student name: Ram
Enter student USN: 22IS001
Enter Subject 1 Marks: 34
Enter Subject 2 Marks: 45
Enter Subject 3 Marks: 43
Student Details:
Name: Ram
USN: 22IS001
Marks: 34 45 43
Total Marks: 122
Percentage: 40.666666666666664 %
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:
from datetime import date
name = input("Enter the name of the person : ")
DOB = int(input("Enter his year of birth : "))
curYear = [Link]().year
age = curYear - DOB
if (age > 60):
print(name, "aged", age, "years is a Senior Citizen.")
else:
print(name, "aged", age, "years is not a Senior Citizen.")
Output
Enter the name of the person : Ram
Enter his year of birth : 1962
Ram aged 61 years is a Senior Citizen.
2. a. Develop a program to generate Fibonacci sequence of length (N). Read N from the console.
Program
f1 = 0
f2 = 1
n = int(input("Enter an Integer : "))
for i in range(n):
print(f1, end=' ')
fib = f1 + f2
f1 = f2
f2 = fib
Output
Enter an Integer : 7
0 1 1 2 3 5 8
b. Write a function to calculate factorial of a number. Develop a program to compute binomial coefficient
(Given N and R).
Program
def fact(n):
if n == 0:
return 1
else:
return n * fact(n-1)
n = int(input("Enter the value of N : "))
r = int(input("Enter the value of R (R cannot be -ive or > N): "))
nCr = fact(n)//(fact(r)*fact(n-r))
print(n,'C',r," = ",nCr)
Output
Enter the value of N : 5
Enter the value of R (R cannot be -ive or > N): 3
5 C 3 = 10
3. Read N numbers from the console and create a list. Develop a program to print mean, variance and
standard deviation with suitable messages.
Program
from math import sqrt
myList = []
tot = 0
n=int(input('Enter the Number of items:'))
print('Enter ', n, ' the Items:')
for i in range(n):
item = int(input())
myList += [item]#append()
tot += item
mean = tot / n
tot = 0
for item in myList:
tot += (item - mean) * (item - mean)
var = tot / n
std = sqrt(var)
print("Mean =", mean)
print("Variance =", var)
print("Standard Deviation =",std)
Output
Enter the Number of items:5
Enter 5 the Items:
12
21
18
15
17
Mean = 16.6
Variance = 9.04
Standard Deviation = 3.0066592756745814
4. Read a multi-digit number (as chars) from the console. Develop a program to print the frequency of
each digit with suitable message.
Program
num = int(input("Enter a multi-digit number: "))
freq = {}
num = str(num)
for digit in num:
freq[digit] = [Link](digit, 0) + 1
print("Frequency of each digit:")
for digit, count in sorted([Link]()):
print("Digit",digit,": ",count, "times")
Output
Enter a multi-digit number: 322311
Frequency of each digit:
Digit 1 : 2 times
Digit 2 : 2 times
Digit 3 : 2 times
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]
Program
import sys
import string
import [Link]
fname = input("Enter the filename : ")
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 + ' '
wordFreq = {}
wordList = [Link]()
#Calculate word Frequency
for word in wordList:
if word not in [Link]():
wordFreq[word] = 1
else:
wordFreq[word] += 1
sortedWordFreq = sorted([Link](), key=lambda x:x[1],
reverse=True )
print("10 most frequently appearing words with their count")
count=0
for i in range(10):
print(sortedWordFreq[i][0], "occurs", sortedWordFreq[i][1],
"times")
Output
Enter the filename : [Link]
10 most frequently appearing words with their count
Kumar occurs 4 times
Nair occurs 2 times
Reddy occurs 2 times
Rao occurs 2 times
Suresh occurs 1 times
Deepika occurs 1 times
Gowda occurs 1 times
Rajesh occurs 1 times
Shweta occurs 1 times
Jain occurs 1 times
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()].
Program
import [Link]
import sys
fname = input("Enter the filename to sort: ")#input file
if not [Link](fname):
print("File", fname, "doesn't exists")
[Link](0)
infile = open(fname, "r")#read mode
lines = [Link]()#list of lines from file
[Link]() # Close the input file
lineList = []#Empty List
for line in lines:
[Link]([Link]())# remove '\n'
[Link]()#Sort the list
outfile = open("[Link]","w+")#write and read mode
if not [Link](fname):
print("Not able to create [Link]")
[Link](0)
for line in lineList:
[Link](line + "\n")
[Link](0,0)#move file pointer to beginning
fstr= [Link]()# read file content as a string
print("[Link] contains", len(lineList),"Lines:")#[Link]('\n')
[Link]()
Output
[Link]
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.
Program
import os
import sys
import pathlib
import zipfile
dirName = input("Enter Directory name to backup: ")
if not [Link](dirName):
print("Directory", dirName, "doesn't exists")
[Link](0)
curDir = [Link](dirName)
with [Link]("[Link]", mode="w") as archive:
for file_path in [Link]("*"):
print(file_path)
[Link](file_path)
if [Link]("[Link]"):
print("Archive [Link] created successfully")
else:
print("Error in creating zip archive")
Output
Enter Directory name to backup: d:\\svce\\
Archive [Link] created successfully
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.
Program
def divExp(a, b):
assert a > 0, "Assertion Error: a should be > 0"
if b == 0: raise ValueError("Value Error: b = 0")
return (a / b)
try:
a = float(input("Enter the value of a: "))
b = float(input("Enter the value of b: "))
print("Result c = ", divExp(a, b))
except ValueError as ve:
print(ve)
except AssertionError as ae:
print(ae)
except Exception as e:
print("Unexpected Error : May be input value ", e)
Output
Enter the value of a: 4
Enter the value of b: 2
Result c = 2.0
Enter the value of a: 4
Enter the value of b: 0
Value Error: b = 0
Enter the value of a: 0
Enter the value of b: 2
Assertion Error: a should be > 0
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.
Program
import sys
class Complex:
def __init__(self, rp=0, ip=0):
self.r = rp
self.i = ip
def __str__(self):
sign = "+" if self.i >= 0 else "-"
return f"{self.r} {sign} {abs(self.i)}i"
def __add__(self, cn):
return Complex(self.r+cn.r, self.i+cn.i)
while True:
n = int(input("Enter the number of complex numbers (N >= 2): "))
if n >= 2:
break
print("N must be >= 2")
res = Complex()
for i in range(n):
try:
rp = int(input(f"Enter Complex No {i+1} Real Part:"))
ip = int(input(f"Enter Complex No {i+1} Imaginary Part:"))
except:
print("Error: Input only Integer Value")
[Link]()
cn = Complex(rp,ip)
res += cn
print(f"The Resultant Complex No: {res}"))
Output
Enter the number of complex numbers (N >= 2): 3
Enter Complex No 1 Real Part:1
Enter Complex No 1 Imaginary Part:2
Enter Complex No 2 Real Part:3
Enter Complex No 2 Imaginary Part:4
Enter Complex No 3 Real Part:5
Enter Complex No 3 Imaginary Part:6
The Resultant Complex No: 9 + 12i
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.]
Program
class Student:
def __init__(self, name = "", usn = "", marks = [0,0,0,0]):
[Link] = name
[Link] = usn
[Link] = marks
perct = 0
def getMarks(self):
[Link] = input("Enter student USN : ")
[Link] = input("Enter student Name : ")
[Link][0] = int(input("Enter mark in Subject 1 : "))
[Link][1] = int(input("Enter mark in Subject 2 : "))
[Link][2] = int(input("Enter mark in Subject 3 : "))
[Link][3] = [Link][0] + [Link][1] + [Link][2]
def disp(self):
perct = [Link][3]/3
spcstr = "=" * 70
print(spcstr)
print("Sri Venkateshwara College of Engineering".center(70))
print("SCORE CARD DETAILS".center(70))
spcstr = "-" * 70
print(spcstr)
print("%15s"%("NAME"), "%10s"%("USN"), "%8s"%"Subject1",
"%8s"%"Subject2","%8s"%"Subject3","%5s"%"TOTAL",
"%10s"%("Percentage"))
print(spcstr)
print("%15s"%[Link], "%10s"%[Link],
"%8d"%[Link][0],"%8d"%[Link][1],
"%8d"%[Link][2],"%5d"%[Link][3],
"%10.2f"%perct)
print(spcstr)
print("Class Teacher".ljust(70))
spcstr = "=" * 70
print(spcstr)
s = Student()
[Link]()
[Link]()
Output
Enter student USN : 22is090
Enter student Name : Ram
Enter mark in Subject 1 : 34
Enter mark in Subject 2 : 45
Enter mark in Subject 3 : 43
======================================================================
Sri Venkateshwara College of Engineering
SCORE CARD DETAILS
----------------------------------------------------------------------
NAME USN Subject1 Subject2 Subject3 TOTAL Percentage
----------------------------------------------------------------------
Ram 22is090 34 45 43 122 40.67
----------------------------------------------------------------------
Class Teacher
======================================================================