Python Lab Manual Final
Python Lab Manual Final
II- Semester
Prepared by
Prof. Nethravathy V
Prof. Vidyashree A L
Prof. Geetha R
BANGALORE INSTITUTE OF TECHNOLOGY
(Affiliated to Visvesvaraya Technological University – VTU )
K.R. Road, V.V. Puram, Bengaluru – 560 004. Phone: 26613237/26615865 Fax:
22426796
Vision
Establish and develop the Institute as the Centre of higher learning, ever abreast with expanding
horizon of knowledge in the field of Engineering and Technology with entrepreneurial thinking,
leadership excellence for life-long success and solve societal problems.
Mission
1. Provide high quality education in the Engineering disciplines from the undergraduate
through doctoral levels with creative academic and professional programs.
2. Develop the Institute as a leader in Science, Engineering, Technology, Management and
Research and apply knowledge for the benefit of society.
3. Establish mutual beneficial partnerships with Industry, Alumni, Local, State and Central
Governments by Public Service Assistance and Collaborative Research.
4. Inculcate personality development through sports, cultural and extracurricular activities and
engage in social, economic and professional challenges.
BANGALORE INSTITUTE OF TECHNOLOGY
(Affiliated to Visvesvaraya Technological University – VTU )
K.R. Road, V.V. Puram, Bengaluru – 560 004. Phone: 26613237/26615865 Fax:
22426796
VISION:
To be a center of excellence in computer engineering education, empowering graduates as
highly skilled professionals.
MISSION:
1. To provide a platform for effective learning with emphasis on technical excellence.
2. To train the students to meet current industrial standards and adapt to emerging
technologies.
3. To instill the drive for higher learning and research initiatives.
4. To inculcate the qualities of leadership and Entrepreneurship.
1. The graduates of the program will have the ability to build software products by
applying theoretical concepts and programming skills.
2. The graduates of the program will have the ability to pursue higher
Program Outcomes
CLO1. Learn the syntax and semantics of the Python programming language.
CLO2. Illustrate the process of structuring the data using lists, tuples
CLO3. Appraise the need for working with various documents like Excel, PDF, Word and Others.
CLO4. Demonstrate the use of built-in functions to navigate the file system.
CLO5. Implement the Object Oriented Programming concepts in Python.
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2
21CS32 CO1
CO2
CO3
CO4
Python Programming Laboratory
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.]
BPLCK205B Python Programming Laboratory
SCHEDULE OF EXPERIMENTS
LABORATORY
General Lab Guidelines:
1. Conduct yourself in a responsible manner at all times in the laboratory. Intentional
misconduct will lead to exclusion from the lab.
2. Do not wander around, or distract other students, or interfere with the laboratory
experiments of other students.
3. Read the handout and procedures before starting the experiments. Follow all written
and verbal instructions carefully.
4. If you do not understand the procedures, ask the instructor or teaching assistant.
Attendance in all the labs is mandatory, absence permitted only with prior permission
from the Class teacher.
5. The workplace has to be tidy before, during and after the experiment.
6. Do not eat food, drink beverages or chew gum in the laboratory.
7. Every student should know the location and operating procedures of all Safety
equipment including First Aid Kit and Fire extinguisher.
DO’S:-
1. An ID card is a must.
2. Keep your belongings in a designated area.
3. Sign the log book when you enter/leave the laboratory.
4. Records have to be submitted every week for evaluation.
5. The program to be executed in the respective lab session has to be written in the lab
observation copy beforehand.
6. After the lab session, shut down the computers.
7. Report any problem in system (if any) to the person in-charge
DON'TS:-
1. Do not insert metal objects such as clips, pins and needles into the computer
casings(They may cause fire) and should not attempt to repair, open, tamper or interfere
with any of the computer, printing, cabling, or other equipment in the laboratory.
2. Do not change the system settings and keyboard keys.
3. Do not upload, delete or alter any software/ system files on laboratory computers.
4. No additional material should be carried by the students during regular labs.
5. Do not open any irrelevant websites in labs.
6. Do not use a flash drive on lab computers without the consent of the lab instructor.
7. Students are not allowed to work in the Laboratory alone or without the presence of the
instructor/teaching assistant.
PYTHON PROGRAMMING
Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.
It is used for:
Why Python?
• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with fewer lines than
some other programming languages.
• Python runs on an interpreter system, meaning that code can be executed as soon as it
is written. This means that prototyping can be very quick.
• Python can be treated in a procedural way, an object-oriented way or a functional
way.
Python Install
To check if you have python installed on a Windows PC, search in the start bar for Python or
run the following on the Command Line (cmd.exe):
To check if you have python installed on a Linux or Mac, then on linux open the command
line or on Mac open the Terminal and type:
python --version
Python Syntax
Or by creating a python file on the server, using the .py file extension, and running it in the
Command Line:
Python Indentation
Where in other programming languages the indentation in code is for readability only, the
indentation in Python is very important.
if 5 > 2:
print("Five is greater than two!")
Python Comments
• Creating a Comment
#This is a comment
print("Hello, World!")
Multiline Comments
#This is a comment
#written in
#more than just one line
print("Hello, World!")
Python Variables
Creating Variables
x=5
y = "John"
print(x)
print(y)
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
Python Strings
Strings in python are surrounded by either single quotation marks, or double quotation marks.
Python Booleans
Boolean Values
You can evaluate any expression in Python, and get one of two answers, True or False.
print(10 > 9)
print(10 == 9)
print(10 < 9)
Python Operators
In the example below, we use the + operator to add together two values:
print(10 + 5)
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
Python Lists
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3
are Tuple, Set, and Dictionary, all with different qualities and usage.
• Equals: a == b
• Not Equals: a != b
Python Loops
• while loops
• for loops
while Loop
With the while loop we can execute a set of statements as long as a condition is true.
i=1
while i < 6:
print(i)
i += 1
For Loops
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set,
or a string).
This is less like the for keyword in other programming languages, and works more like an
iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set
etc.
SAMPLE PROGRAMS
x=4
y=3
print (x + y)
temp = x
x=y
y = temp
if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))
# initialize sum
sum = 0
LAB PROGRAMS
PROGRAM 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
=================================
=========================
Name : RAMESH
USN : 1SI22CS036
Marks 1 : 87
Marks 2 : 78
Marks 3 : 65
Total : 230
Percent : 76.67
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
curYear = date.today().year
perAge = curYear - perDOB
Output
=================================
PROGRAM 2
A. Develop a program to generate Fibonacci sequence of length (N). Read N from the
console.
Output
Enter the Fibonacci sequence length to be generated : 8
The Fibonacci series with 8 terms is :
5 0 1 1 2 3 5 8 13
Enter the Fibonacci sequence length to be generated : 5
The Fibonacci series with 5 terms is :
0 1123
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
Enter the value of N : 7
Enter the value of R (R cannot be negative or greater than N): 5
7C5 = 21
PROGRAM 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 : "))
myList.append(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)
Output
Mean = 58.4
Variance = 642.64
Standard Deviation = 25.35
PROGRAM 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
Enter a number : 234939
The number entered is : 234939
4 occurs 1 times
9 occurs 2 times
3 occurs 2 times
2 occurs 1 times
PROGRAM 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 also provided
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 + '' #replace punctuations and \n with space
wordFreq = {}
wordList = filecontents.split()
#Calculate word Frequency
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
Enter the filename : text.txt
===================================================
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
PROGRAM 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.path
import sys
fname = input("Enter the filename whose contents are to be sorted : ") #sample
file unsorted.txt also provided
if not os.path.isfile(fname):
print("File", fname, "doesn’t exists")
sys.exit(0)
myList = infile.readlines()
# print(myList)
lineList.sort()
#Write sorted contents to new file sorted.txt
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
Enter the filename whose contents are to be sorted : unsorted.txt
To be or not to be.
Tuesday is the Wednesday of the rest of your life.
What is the square root of 4bˆ2?
You display the wonderful traits of charm and courtesy.
You may be recognized soon. Hide.
PROGRAM 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 exists")
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
PROGRAM 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 greater than 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 : "))
OUTPUT
Enter a value for a : 7
Enter a value for b : 6
7 / 6 = 1.1666666666666667
PROGRAM 9
Define a function which takes 2 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 greater than 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 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 main():
c1 = Complex(3,5)
c2 = Complex(6,4)
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()
main()
Output
Complex Number 1
(3)+i(5)
Complex Number 2
(6)+i(4)
Sum of two Complex Numbers
(9)+i(9)
PROGRAM 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]):
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"%"T
OTAL","%12s"%("PERCENTAGE"))
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"%percentage)
print(spcstr)
def main():
s1 = Student()
s1.getMarks()
s1.display()
main()
Output
Enter student Name : vi
Enter student USN : 123
Enter marks in Subject 1 : 23
Enter marks in Subject 2 : 22
Enter marks in Subject 3 : 24
=================================================================
================
SCORE CARD DETAILS
=================================================================
================
NAME USN MARKS1 MARKS2 MARKS3 TOTAL PERCENTAGE
=================================================================
================
vi 123 23 22 24 69 23.00
=================================================================
================