Python Lab Manual 2025
Python Lab Manual 2025
AND MANAGEMENT
Udayapura, Kanakapura Road, Opp. Art of Living, Bangalore – 560082
(Affliated to VTU, Belagavi, Approved by AICTE, New Delhi, Accredited by NBA, New Delhi)
(Autonomous to VTU)
2024-2025
Introduction to Python Programming
Laboratory Manual
(23PLCS21)
DAYANANDA SAGAR ACADEMY OF TECHNOLOGY &
MANAGEMENT
(Affiliated to Visvesvaraya Technological University, Belagavi and Approved by AICTE, New
Delhi, Accredited by NBA for 3 years, New Delhi)
1. Creating an academic environment to develop the younger generation and providing quality
professional engineering education at an affordable cost.
2. Create necessary infrastructure on a continuous basis the professional education with the
changing needs of society.
3. Optimum utilization of the infrastructure and resources to achieve excellence in the
engineering courses.
4. Monitor continuously the growth in technology parts of the world and address all aspects of
development of human resource (both from academic and supporting staff) and students to be in
tune with state of the art technology and engineering practices.
5. Facilitate greater Industry, Institute, and Interaction so as to empower the students with
practical knowledge.
6. Institute various quality assurance systems.
7. Adopting learning beyond curriculum process.
8. Initiate systems of learning which are based on enable students to acquire skills relevant to their
career.
9. To continuous monitor, asses evaluate the various academic programs adopting outcome-based
education.
INTRODUCTION TO PYTHON PROGRAMMING
LABORATORY
Outcome-Based Education (OBE) and Choice Based Credit System (CBCS)
(Effective from the academic year 2023 – 24)
List of problems for which students should develop the program and execute in the
Laboratory
Sl. No. Experiments/Programs Page No.
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.
1 1
b. Develop a Python program to check whether a given number is palindrome or not and
also count the number of occurrences of each digit in the input number
a. Develop a program to generate Fibonacci sequence of length (N). Read N from the
2 console. 4
b. Write a function to calculate factorial of a number with and without recursion.
a. Read N numbers from the console and create a list. Develop a program to print mean,
variance and standard deviation with suitable messages using functions.
3 10
b. Develop a python program to convert binary to decimal, octal to hexadecimal using
functions.
Read a multi-digit number (as chars) from the console. Develop a program to print the
4 14
frequency of each digit with suitable messages.
a. 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]
5 16
b. 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(), read lines(), and write()].
6 b. Write a function named DivExp which takes TWO parameters a, b and returns a value c 17
(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.
a. Develop a Python program to demonstrate find all function and character class using
7 regex module. 19
b. Develop a python program that could search the text in a file for phone numbers
(+919900889977) and email addresses ([email protected]).
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
8 24
‘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:
9 Use list to store the marks in three subjects and total marks. Use init () method to 29
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.].
CIE for Introduction to Python Programming (Integrated Professional Core Course (IPCC)):
This Course refers to Professional Theory Core Course Integrated with Practical Component Credit for this
course can be 03 and its Teaching Learning hours (L: T: P: PJ) can be considered as (2: 0: 2: 0).
Note: L- Theory Lecture, T- Tutorial, P-Practical, PJ-Project, CIE: Continuous Internal Evaluation, SEE:
Semester End Examination.
PYTHON PROGRAMMING LABORATORY 23PLCS21
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.
Ans 1:
n=int(input("Enter number:"))
temp=n
rev=0
while(n>0):
rem=n%10
rev=rev*10+rem
n=n//10
if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")
n=temp
for i in range(10):
temp=n
count=0
while temp>0:
if(temp % 10 == i):
count = count + 1
temp = temp // 10
print( i, "occurs", count, "times in the input")
Output
Run 1 Run 2:
Enter number:122267484 Enter number:1335331
The number isn't a palindrome! The number is a palindrome!
0 occurs 0 times in the input 0 occurs 0 times in the input
1 occurs 1 times in the input 1 occurs 2 times in the input
2 occurs 3 times in the input 2 occurs 0 times in the input
3 occurs 0 times in the input 3 occurs 4 times in the input
4 occurs 2 times in the input 4 occurs 0 times in the input
5 occurs 0 times in the input 5 occurs 1 times in the input
6 occurs 1 times in the input 6 occurs 0 times in the input
7 occurs 1 times in the input 7 occurs 0 times in the input
8 occurs 1 times in the input 8 occurs 0 times in the input
9 occurs 0 times in the input 9 occurs 0 times in the input
Ans 2:
val = int(input("Enter a value : "))
str_val = str(val)
if str_val == str_val[::-1]:
print("Palindrome")
else:
print("Not Palindrome")
for i in range(10):
if str_val.count(str(i)) > 0:
print(str(i), "appears", str_val.count(str(i)), "times");
Output
Run 1 Run 2
Enter a value : 13531 Enter a value : 123134
Palindrome Not Palindrome
1 appears 2 times 1 appears 2 times
3 appears 2 times 2 appears 1 times
5 appears 1 times 3 appears 2 times
4 appears 1 times
PROGRAM-2
a) Develop a program to generate Fibonacci sequence of length (N). Read N from the
console.
def fibonacci(num):
if num == 0:
return 0
elif num == 1:
return 1
else:
return fibonacci(num-2)+fibonacci(num-1)
n = int(input("Enter the value of N : "))
for i in range(0, n):
print(fibonacci (i), end=" ")
Output
Enter the value of N : 5
01123
b) Write a function to calculate the factorial of a number with and without recursion.
With Recursion:
def fact(num):
if num == 0:
return 1
else:
return num * fact(num-1)
n = int(input("Enter the value of N : "))
factorial = fact(n)
print(n,'!'," = ",factorial,sep="")
Output
Enter the value of N : 5
5! = 120
Without recursion:
def fact(num):
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
return
elif num == 0:
return 1
else:
factorial=1
for i in range(1,num + 1):
factorial = factorial*i
return factorial
num = int(input("Enter a number: "))
factorial = fact(num)
print("The factorial of",num,"is",factorial)
Output
Enter a number: 6
The factorial of 6 is 720
PROGRAM-3
a) Read N numbers from the console and create a list. Develop a program to print
mean, variance and standard deviation with suitable messages using functions.
Ans 1(using built-in functions):
import statistics
Numlist = []
n = int(input("Enter the value of n : "))
for i in range(0, n):
ele = int(input('Enter number '+ str(i+1)))
Numlist.append(ele)
print('The list of elements is',Numlist)
print('Mean=',statistics.mean(Numlist));
print('Variance=',statistics.variance(Numlist));
print('Standard deviation=',statistics.stdev(Numlist));
Output:
Enter the value of n : 5
Enter number 1:10
Enter number 2:20
Enter number 3:30
Enter number 4:5
Enter number 5:15
The list of elements is [10, 20, 30, 5, 15]
Mean= 16
Variance= 92.5
Standard deviation= 9.617692030835672
def std_dev(List):
return math.sqrt(variance(List))
Numlist = []
n = int(input("Enter the value of n : "))
for i in range(0, n):
ele = int(input('Enter number '+ str(i+1)))
Numlist.append(ele)
print('The list is', Numlist)
print('mean is',mean(Numlist))
print('variance is',variance(Numlist))
print('Standard deviation is',std_dev(Numlist))
Output
Enter the value of n : 5
Enter number 1:5
Enter number 2:15
Enter number 3:10
Enter number 4:20
Enter number 5:30
The list is [5, 15, 10, 20, 30]
mean is 16.0
variance is 92.5
Standard deviation is 9.617692030835672
Output
Enter a Binary Number: 10001
Equivalent Decimal Value = 17
Enter an Octal Number: 756
Equivalent Hexadecimal Value = 1EE
Ans 2:
def BinToDec(b):
try:
return int(b, 2)
except ValueError:
print('Not a valid binary number')
bnum = input("Enter the Binary Number: ")
dnum = BinToDec(bnum)
print("Equivalent Decimal Value = ", dnum)
def OctToHex(o):
try:
return hex(int(o, 8))
except ValueError:
print('Not a valid Octal number')
onum = input("Enter Octal Number: ")
hnum = OctToHex(onum)
try:
print("\nEquivalent Hexadecimal Value =", hnum[2:].upper())
except TypeError:
print()
Output:
Enter the Binary Number: 45
Not a valid binary number
Equivalent Decimal Value = None
Enter Octal Number: 89
Not a valid Octal number
PROGRAM-4
Read a multi-digit number (as chars) from the console. Develop a program to print the
frequency of each digit with suitable messages.
Program:
input=str(input('Enter a string of digits: '))
List=['1','2','3','4','5','6','7','8','9','0']
for dig in List:
count=0
for character in input:
if dig==character:
count+=1
print('Number of ',dig, ': ' ,count)
Output:
Enter string: 12334545645768787989
Number of 1: 1
Number of 2: 1
Number of 3: 2
Number of 4: 3
Number of 5: 3
Number of 6: 2
Number of 7: 3
Number of 8: 3
Number of 9: 2
Number of 0: 0
PROGRAM-5
a) 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]
fname=input('Enter file directory/name: ')
c=[]
d={}
with open(fname,'r') as f:
content=f.read()
word=content.split()
for i in word:
c.append(i)
for i in c:
count=0
for j in c:
if i==j:
count+=1
d[i]=count
b) 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(), read lines(), and write()].
PROGRAM - 6
a) 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 shutil
name=input('Enter zip file name: ')
directory=input('Enter file directory: ')
shutil.make_archive(name,'zip',directory)
Output
Enter zip file name: eggs
Enter file directory: eggs
'C:\\Users\\rama\\eggs.zip'
b) 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)
Run 1:
Enter a value for a : 10
Enter a value for b : 5
10 / 5 = 2.0
Run 2:
Enter a value for a : -1
Run 3:
Enter a value for a : 20
Enter a value for b : 0
Value of b cannot be zero
PROGRAM-7
a) Develop a Python program to demonstrate find all function and character class
using regex module.
Metacharacters
Program
import re
input_str = "This is sample string1"
pattern="[i][a-z]" #try different character classes
result = re.findall(pattern, input_str)
print("Matching value", result)
Output
Matching value ['is', 'is', 'in']
b) Develop a python program that could search the text in a file for phone numbers
(+919900889977) and email addresses ([email protected]).
import re
# Define the regular expression for phone numbers
phone_regex = re.compile(r'\+\d{12}')
# Define the regular expression for email addresses
email_regex = re.compile(r'[A-Za-z0-9._]+@[A-Za-z0-9]+\.[A-Z|a-z]{2,}')
PROGRAM-8
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, a, b):
self.real=a
self.imaginary=b
def add(self,C1):
temp=Complex(0, 0)
temp.real = self.real + C1.real;
temp.imaginary = self.imaginary + C1.imaginary;
return temp;
def displayComplex(self):
print(self.real,'+i',self.imaginary, sep="")
complexList = []
n=int(input('Enter the value of n: '))
if n>=2:
for i in range(n):
a=int(input('Enter real part of the complex number '+str(i+1)+':'))
b=int(input('Enter imaginary part of the complex number '+str(i+1)+':'))
Complex_Obj=Complex(a,b)
complexList.append(Complex_Obj)
print("\nEntered Complex numbers are : ")
for obj in complexList:
obj. displayComplex()
sumObj = Complex(0,0)
for obj in complexList:
sumObj=sumObj.add(obj)
print("\nSum of N complex numbers is", end = " ")
sumObj.displayComplex()
else:
print('Invalid input. Enter number greater than 2')
Output
Enter the value of n: 2
Enter real part of the complex number 1:1
Enter imaginary part of the complex number 1:2
Enter real part of the complex number 2:2
Enter imaginary part of the complex number 2:4
PROGRAM-9
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):
self.name=name
self.usn=usn
self.marks=[]
self.subjects=[]
def enterMarks(self):
for i in range(3):
sub=input('Enter subject: ')
self.subjects.append(sub)
mark=int(input('Enter marks of %s in %s: '%(self.name,sub)))
self.marks.append(mark)
def total(self):
total=self.marks[0]+self.marks[1]+self.marks[2]
return total
def per(self):
per=(self.marks[0]+self.marks[1]+self.marks[2])/3
return per
def disp(self):
print(self.name,'USN:',self.usn,'got',self.marks,'in',self.subjects)
print('Total marks:',self.total())
print('Percentage:',self.per())
name=input('Enter name of student: ')
usn=input('Enter USN: ')
s1=Student(name,usn)
s1.enterMarks()
s1.disp()
OUTPUT:
Enter name of student: ram
Enter USN: 122
Enter subject: maths
Enter marks of ram in maths: 12
Enter subject: science
Enter marks of ram in science : 13
Enter subject: physics
Enter marks of ram in physics: 11
ram USN: 122 got [12, 13, 11] in ['maths', 'science ', 'physics']
Total marks: 36
Percentage: 12.0
PROGRAM-10
Develop a program to convert list and dictionary into NumPy array
Code to read input into the dictionary
import numpy
n = int(input("Enter number of elements to insert into the dictionary: "))
my_dict= {}
for x in range(n):
new_key =input('Enter new key: ')
new_value = input('Enter new value: ')
my_dict[new_key] = new_value
lst = []
n = int(input("Enter number of elements to insert into the list : "))
for i in range(0, n):
ele = int(input('Enter an item: '))
lst.append(ele)
lst_arr = numpy.array(lst)
dict_array = numpy.array(list(my_dict.items()))
print ("List: ", lst)
print ("List Array: ", lst_arr)
print ("Dictionary: ", my_dict)
print ("Dictionary Array: ", dict_array)
OUTPUT:
Enter number of elements to insert into the dictionary: 4
Enter new key: 1
Enter new value: ise
Enter new key: 2
Enter new value: cse
Enter new key: 3
Enter new value: mech
Enter new key: 4
Enter new value: civil
Enter number of elements to insert into the list : 6
Enter an item: 34
Enter an item: 12
Enter an item: 45
Enter an item: 12
Enter an item: 65
Enter an item: 78