Vtu Python Lab Manual for 1st and 2nd Se
Vtu Python Lab Manual for 1st and 2nd Se
INTRODUCTION TO
PYTHON PROGRAMMING
LABORATORY MANUAL
Introduction to Python Programming
Subject code:
BPLCK105B/205B
[As per Choice Based Credit System (CBCS) scheme]
(Effective from the academic year 2023 -2024)
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.
Student.py
OUTPUT:
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.
Age.py
currentyear = date.today().year
Age = currentyear - DOB
OUTPUT:
Enter the name of the person : Naveen
Enter the year of birth : 1992
Naveen is not a Senior Citizen.
firstnumber = 0
secondnumber = 1
print("The Fibonacci series is :")
print(firstnumber)
print(secondnumber)
for i in range(2,n):
newnumber= firstnumber + secondnumber
print(newnumber)
firstnumber = secondnumber
secondnumber = newnumber
OUTPUT:
def fact(num):
if num == 0:
return 1
else:
return num * fact(num - 1)
OUTPUT:
3. Read N numbers from the console and create a list. Develop a program to
print mean, variance and standard deviation with suitable messages.
mean.py
import math
L = []
n = int(input("Enter the number of elements: "))
for i in range(n):
val = int(input("Enter the element : "))
L.append(val)
mean = sum(L) / n
total = 0
for elem in L:
total += (elem - mean) ** 2
variance = total / n
stddev = math.sqrt(variance)
OUTPUT:
4. Read a multi-digit number (as chars) from the console. Develop a program
to print the frequency of each digit with suitable message.
count.py
for i in n:
if i in freq:
freq[i] += 1
else:
freq[i] = 1
# printing result
print("Count of all characters is :", freq)
OUTPUT:
Enter a number : 1234469
Count of all characters is : {'1': 1, '2': 1, '3': 1, '4': 2, '6': 1, '9': 1}
Count.py
import operator
fname = input('Enter the file name: ')
try:
fhand = open(fname)
counts = dict()
for line in fhand:
words = line.split()
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
INPUT:
input.txt
Bapuji Educational Association (BEA) is a conglomerate of over 50
educational institutions across the city of Davangere. The Association was
established in the year 1958 with the inception of a first grade college in
Davangere. Two medical colleges, two dental colleges, an engineering college
- Bapuji Institute of Engineering & Technology (BIET) and numerous other
colleges are associated with association. The Bapuji Educational Association
is one of the oldest and most prestigious educational associations in
Karnataka. Today the association has grown to be a big tree, like the banyan,
with all its twigs and branches. It runs schools and colleges right from
Nursery to Post Graduate courses, from Diploma to Engineering, Nursing to
Medical.
OUTPUT:
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()].
Sorting.py
f = open("input.txt")
words = []
for line in f:
temp = line.split()
for i in temp:
words.append(i)
f.close()
words.sort()
outfile = open("output.txt", "w")
for i in words:
outfile.writelines(i)
outfile.writelines(" ")
outfile.close()
INPUT: input.txt
OUTPUT: output.txt
import os
import zipfile
zf = zipfile.ZipFile("myzipfile.zip", "w")
for foldername, subfolders, files in os.walk("mydirectory"):
for filename in files:
zf.write(os.path.join(foldername, filename))
print("Zip file is created")
zf.close()
Output:
Zip file is created
Division.py
# Raise an exception if b is 0
if b == 0:
raise ZeroDivisionError("Division by zero is
not allowed.")
except Exception as e:
print(e)
OUTPUT:
1) Enter the value of a: 20
Enter the value of b: 2
The result of division is: 10.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.
Complex.py
class Complex:
def _ _init_ _(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def __str__(self):
return f"{self.real} + {self.imaginary}i"
def read(n):
complex_numbers = []
for i in range(n):
real = float(input(f"Enter the real part of
complex number {i + 1}: "))
imaginary = float(input(f"Enter the imaginary part of
complex number {i + 1}: "))
complex_numbers.append(Complex(real, imaginary))
return complex_numbers
def sum(complex_numbers):
total = Complex(0, 0)
for cn in complex_numbers:
total = total + cn
return total
complex_numbers = read(n)
total = sum(complex_numbers)
print("The sum of the complex numbers is:", total)
OUTPUT:
1) Enter the number of complex numbers (N >= 2): 2
Enter the real part of complex number 1: 2
Enter the imaginary part of complex number 1: 3
Enter the real part of complex number 2: 4
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.]
Student.py
class Student:
def _ _init_ _(self, name, usn):
self.name = name
self.usn = usn
self.marks = [0, 0, 0]
self.total = 0
self.percentage = 0.0
def getMarks(self):
for i in range(3):
self.marks[i] = float(input(f"Enter marks for subject {i+1}: "))
def calculate(self):
self.total = sum(self.marks)
self.percentage = self.total / 3 # Assuming each subject is out of 100
def display(self):
print("\nScore Card Details")
print("-------------------")
print("Name:", self.name)
print("USN:", self.usn)
print("Marks in subjects:", self.marks)
print("Total marks:", self.total)
print("Percentage:", self.percentage)
OUTPUT:
Enter the student's name: Anil
Enter the student's USN: 123456
Enter marks for subject 1: 22
Enter marks for subject 2: 17
Enter marks for subject 3: 24