lOMoARcPSD|48293131
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [BPLCK105B/205B]
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)
Inshu 1
lOMoARcPSD|48293131
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [BPLCK105B/205B]
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
Name = input("Enter the name of the student : ")
USN = input("Enter the USN of the student : ")
Marks1 = int(input("Enter marks in Subject 1 : "))
Marks2 = int(input("Enter marks in Subject 2 : "))
Marks3 = int(input("Enter marks in Subject 3 : "))
print("Student Details\n=========================")
print("Name :", Name) print("USN :", USN)
print("Marks 1 :", Marks1) print("Marks 2 :",
Marks2) print("Marks 3 :", Marks3)
print("Total :", Marks1+Marks2+Marks3) print("Percent
:", ((Marks1+Marks2+Marks3)/3))
OUTPUT:
Enter the name of the student : Naveen
Enter the USN of the student : 12345678
Enter marks in Subject 1 : 50
Enter marks in Subject 2 : 68
Enter marks in Subject 3 : 98
Student Details
=========================
Name : Naveen
USN : 12345678
Marks 1 : 50
Marks 2 : 68
Marks 3 : 98
Total : 216
Percent : 72.0
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.
Inshu 2
lOMoARcPSD|48293131
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [BPLCK105B/205B]
Age.py
from datetime import date
Name = input("Enter the name of the person : ")
DOB = int(input("Enter his year of birth : "))
currentyear = date.today().year
Age = currentyear - DOB
if (Age > 60): print(Name, "is a
Senior Citizen.") else: print(Name,"is
not a Senior Citizen.")
OUTPUT:
Enter the name of the person : Naveen
Enter the year of birth : 1992 Naveen
is not a Senior Citizen.
2. a. Develop a program to generate Fibonacci sequence of length (N). Read
N from the console
Fibonacci.py
Inshu 3
lOMoARcPSD|48293131
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [BPLCK105B/205B]
n = int(input("Enter the Fibonacci sequence length to be
generated : "))
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:
The Fibonacci series is :
0
1
1
2
3
5
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)
Inshu 4
lOMoARcPSD|48293131
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [BPLCK105B/205B]
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, " = ",
nCr)
OUTPUT:
Enter the value of N : 5
Enter the value of R (R cannot be negative or greater than N): 2 5
C 2 = 10.0
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 : "))
Inshu 5
lOMoARcPSD|48293131
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [BPLCK105B/205B]
L.append(val)
print('The length of list1 is', len(L)) print('List
Contents', L)
mean = sum(L) / n
total = 0 for elem in L:
total += (elem - mean) ** 2
variance = total / n stddev =
math.sqrt(variance)
print("Mean =", mean) print("Variance
=", variance) print("Standard
Deviation =", stddev)
OUTPUT:
Enter the number of elements in your list : 4
Enter the element : 10
Enter the element : 20
Enter the element : 30
Enter the element : 40
The length of list1 is 4
List Contents [10, 20, 30, 40]
Mean = 25.0
Variance = 125.0
Standard Deviation = 11.180339887498949
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
n = input("Enter a number : ") freq
= {}
for i in n: if
i in freq:
freq[i] += 1
else:
freq[i] = 1
Inshu 6
lOMoARcPSD|48293131
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [BPLCK105B/205B]
# 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}
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]
Count.py
import operator
fname = input('Enter the file name: ')
try: fhand = open(fname)
counts = dict() for line in fhand:
Inshu 7
lOMoARcPSD|48293131
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [BPLCK105B/205B]
words = line.split()
for word in words: if
word in counts:
counts[word] += 1
else:
counts[word] = 1
counts = sorted(counts.items(), key=operator.itemgetter(1),
reverse=True) for i in range(10):
print(counts[i]) except: print('File cannot be
opened:', fname)
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:
Enter the file name: input.txt
('the', 6)
('of', 5)
('and', 4)
('to', 4)
('Bapuji', 3)
('Association', 3)
Inshu 8
lOMoARcPSD|48293131
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [BPLCK105B/205B]
('a', 3)
('in', 3)
('with', 3)
('Educational', 2)
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
Inshu 9
lOMoARcPSD|48293131
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [BPLCK105B/205B]
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
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: output.txt
& (BEA) (BIET) - 1958 50 Association Association Association Bapuji
Bapuji Bapuji Davangere. Davangere. Diploma Educational Educational
Engineering Engineering, Graduate Institute It Karnataka. Medical.
Nursery Nursing Post Technology The The Today Two a a a across all an
and and and and are associated association association. associations banyan,
be big branches. city college college colleges colleges colleges, colleges,
conglomerate courses, dental educational educational engineering
established first from from grade grown has in in in inception institutions is
is its like medical most numerous of of of of of oldest one other over
prestigious right runs schools the the the the the the to to to to tree, twigs
two was with with with year
Inshu 1
lOMoARcPSD|48293131
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [BPLCK105B/205B]
7. Develop a program to backing up a given folder(Folder in a current
working directory) into a ZIP file by using relevent modules and suitable
methods.
zip.py
import os
import
zipfile
zf = zipfile.ZipFile("myzipfile.zip", "w") for
foldername, subfolders, files in
os.walk("mydirectory"): for filename in files:
Inshu 1
lOMoARcPSD|48293131
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [BPLCK105B/205B]
zf.write(os.path.join(foldername, filename))
print("Zip file is created") zf.close()
Output:
Zip file is created
8. Write a function named DivExp which takes two parameters a, b returns
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.
Division.py
def DivExp(a, b): try: assert a > 0, "a
should be greater than 0."
# Raise an exception if b is 0
if b == 0:
Inshu 1
lOMoARcPSD|48293131
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [BPLCK105B/205B]
raise ZeroDivisionError("Division by zero is
not allowed.")
# Perform the division
c = a / b
print("The result of division is:", c)
except Exception as
e: print(e)
a = int(input('Enter the value of a:')) b
= int(input('Enter the value of b:'))
DivExp(a,b)
OUTPUT:
1) Enter the value of a: 20
Enter the value of b: 2
The result of division is: 10.0
2) Enter the value of a: 0 Enter the value of b: 20 a should be greater than 0.
3) Enter the value of a: 20
Enter the value of b: 0
Division by zero is not allowed.
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
Inshu 1
lOMoARcPSD|48293131
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [BPLCK105B/205B]
self.imaginary = imaginary
def _ _add_ _(self, other): return
Complex(self.real + other.real, self.imaginary +
other.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
n = int(input("Enter the number of complex numbers (N >=
2): ")) if n < 2: print("N must be at least 2.")
exit()
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
Enter the imaginary part of complex number 2: 5
The sum of the complex numbers is: 6.0 + 8.0i
Inshu 1
lOMoARcPSD|48293131
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [BPLCK105B/205B]
Enter the number of complex numbers (N >= 2): 1 N must be at
least 2.
Inshu 1
lOMoARcPSD|48293131
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [BPLCK105B/205B]
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)
name = input("Enter the student's
name: ") usn = input("Enter the
Inshu 16
lOMoARcPSD|48293131
INTRODUCTION TO PYTHON PROGRAMMING LABORATORY [BPLCK105B/205B]
student's USN: ") s = Student(name,
usn)
s.getMarks()
s.calculate()
s.display()
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
Score Card Details
-------------------
Name: Anil
USN: 123456
Marks in subjects: [22.0, 17.0, 24.0]
Total marks: 63.0
Percentage: 21.0
Inshu 17