INTRODUCTION TO PYTHON
PROGRAMMING
LAB MANUAL
Year : 2023 - 2024
Course Code : 22PLC15B/25B
Semester : I
Branch : CSE
Prepared by
Prof. khadeejath Ramzeela , Asst. Professor, Dept. of CSE
P.A.COLLEGE OF ENGINEERING
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
(Approved by AICTE, Affiliated to VTU, NBA Accredited 2019-24,
Recognized by Govt. of Karnataka, Certified to ISO 9001 – 2008
P.A. EDUCATIONAL TRUST (REGD.)
Nadupadav, Near Mangalore University - 574153
2022 -2023
P.A.COLLEGE OF ENGINEERING
VISION OF THE INSTITUTE
PACE is envisaged as a center of evolution for excellence in Technological, Management and
Research Education. The institution aspires to spread universal knowledge through villages and
cities enabling expansion of human resources.
MISSION OF THE INSTITUTE
I1 : To provide career-oriented professional education to produce technically
competentengineers and managers with moral and ethical values.
I2 : To foster and promote an effective learning environment in the campus to be
recognizedas place that encourages excellence and diversity in thoughts and endeavor.
I3 : To provide research and intellectual resources to address problems facing the industry
and the society while advancing the scopes of multidisciplinary applications.
VISION OF THE DEPARTMENT
To be a center of excellence in providing quality education of global standards and be a pioneer in
spreading the knowledge and innovative ideas of Computer Science and Engineering for catering
the industrial demands and societal needs.
MISSION OF THE DEPARTMENT
M1 : To develop competent innovative professionals having effective communication
skillswith proficiency in real world problem solving with leadership traits.
M2 : To impart quality and value based education to reach the expectations of all the
stakeholders through an ever evolving, effective and creative teaching-learning process.
M3 : To undertake salient research works for the establishment of center of excellence in
theField of Computer Science and Engineering and multi-disciplinary areas.
Introduction to Python Programming lab manual
LIST OF EXPERIMENTS
Exp.
No DESCRIPTION
1. 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
1 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
2b) Write a function to calculate factorial of a number. Develop a program to compute
binomial coefficient (Given N and R).
2.
3. 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. 4) Read multi-digit number as char from the console develop a program to print the
frequencyof each digit with suitable message
5. 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. 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. 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. 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. 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. 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.]
Prof Ramzeela 2022-2023 CSE DEPT PACE
Introduction to Python Programming lab manual
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.
# Read student details
name = input("Enter student's name: ")
usn = input("Enter student's USN: ")
print("Enter marks in three subjects:")
marks1 = float(input("Subject 1: "))
marks2 = float(input("Subject 2: "))
marks3 = float(input("Subject 3: "))
# Calculate total marks and percentage
total_marks = marks1 + marks2 + marks3
percentage = (total_marks / 300) * 100
# Display student details, total marks and percentage
print("\nStudent Details:")
print("Name:", name)
print("USN:", usn)
print("Total Marks:", total_marks)
print("Percentage: “, percentage)
Prof Ramzeela 2022-2023 CSE DEPT PACE
Introduction to Python Programming lab manual
1 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.
import datetime
# Read name and year of birth of a person
name = input("Enter name: ")
year_of_birth = int(input("Enter year of birth: "))
# Calculate age
current_year = datetime.datetime.now().year
age = current_year - year_of_birth
# Check if person is a senior citizen
if age >= 60:
print("\n", name,"is a senior citizen.")
else:
print("\n", name, "is not a senior citizen.")
Prof Ramzeela 2022-2023 CSE DEPT PACE
Introduction to Python Programming lab manual
2 a. Develop a program to generate Fibonacci sequence of length (N). Read N from the console
# Program to display the Fibonacci sequence up to n-th term
nterms = int(input("How many terms? "))
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
Prof Ramzeela 2022-2023 CSE DEPT PACE
Introduction to Python Programming lab manual
2b) Write a function to calculate factorial of a number. Develop a program to compute binomial
coefficient (Given N and R).
def factorial(n):
if n == 0:
return 1
return n * factorial(n-1)
def binomial_coefficient(n, r):
return factorial(n) / (factorial(r) * factorial(n-r))
# example usage
n = int(input("Enter the value of n: "))
r = int(input("Enter the value of r: "))
result = binomial_coefficient(n, r)
print("The binomial coefficient is:", result)
Prof Ramzeela 2022-2023 CSE DEPT PACE
Introduction to Python Programming lab manual
3) Read N numbers from the console and create a list. Develop a program to print mean,
variance and standard deviation with suitable messages.
import math
# Read value of N
n = int(input("Enter the number of elements: "))
# Read N numbers from the console and create a list
numbers = [float(input()) for i in range(n)]
# Calculate the mean
mean = sum(numbers) / n
# Calculate the variance
variance = sum((x - mean) ** 2 for x in numbers) / n
# Calculate the standard deviation
std_dev = math.sqrt(variance)
# Print the results
print("\nMean: {:.2f}".format(mean))
print("Variance: {:.2f}".format(variance))
print("Standard deviation: {:.2f}".format(std_dev))
Prof Ramzeela 2022-2023 CSE DEPT PACE
Introduction to Python Programming lab manual
4) Read multi-digit number as char from the console develop a program to print the
frequencyof each digit with suitable message
number = input("Enter a multi-digit number: ")
# Initialize a dictionary to store the frequency of each digit
frequency = {}
# Iterate through each digit in the number
for digit in number:
if digit.isnumeric():
if digit in frequency:
frequency[digit] += 1
else:
frequency[digit] = 1
# Print the frequency of each digit
for key, value in frequency.items():
print("The frequency of digit", key, "is", value)
Prof Ramzeela 2022-2023 CSE DEPT PACE
Introduction to Python Programming lab manual
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 string
from collections import Counter
# Open the file in read mode
with open('file.txt', 'r') as file:
# Read the contents of the file
text = file.read()
# Remove punctuation marks from the line
text = text.translate(text.maketrans("", "", string.punctuation))
# Split the contents of the file into words
words = text.split()
# Count the frequency of each word
word_freq = Counter(words)
# Sort the dictionary in descending order of frequency
sorted_word_freq = dict(sorted(word_freq.items(), key = lambda x: x[1], reverse=True))
# Print the top 10 most frequent words
for word, freq in list(sorted_word_freq.items())[:10]:
print(word, freq)
Prof Ramzeela 2022-2023 CSE DEPT PACE
Introduction to Python Programming lab manual
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()].
with open('file1.txt', 'r') as file1, open('file2.txt', 'w') as file2:
# Read the contents of the first file
lines = file1.readlines()
# Sort the lines
lines.sort()
# Write the sorted lines to the second file
for line in lines:
file2.write(line)
print("File sorted and written successfully!")
Prof Ramzeela 2022-2023 CSE DEPT PACE
Introduction to Python Programming lab manual
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 shutil
def backup_folder(folder_path):
# Get the current working directory
cwd = os.getcwd()
# Create a backup folder
backup_folder_path = os.path.join(cwd, 'backup')
if not os.path.exists(backup_folder_path):
os.makedirs(backup_folder_path)
# Get the name of the folder to be backed up
folder_name = os.path.basename(folder_path)
# Create the ZIP file path
zip_file_path = os.path.join(backup_folder_path, folder_name + '.zip')
# Backup the folder to the ZIP file
shutil.make_archive(zip_file_path, 'zip', folder_path)
#example
backup_folder('testfolder')
Prof Ramzeela 2022-2023 CSE DEPT PACE
Introduction to Python Programming lab manual
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.
def DivExp(a, b):
assert a > 0, "a must be greater than 0"
assert b != 0, "b cannot be 0"
c=a/b
return c
a = float(input("Enter the first value: "))
b = float(input("Enter the second value: "))
try:
result = DivExp(a, b)
print("Result:", result)
except AssertionError as e:
print("Assertion Error:", e)
except ZeroDivisionError as e:
print("Division by zero error:", e)
Prof Ramzeela 2022-2023 CSE DEPT PACE
Introduction to Python Programming lab manual
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
class Complex:
def init (self, real, imag):
self.real = real
self.imag = imag
def add_complex(z1, z2):
real = z1.real + z2.real
imag = z1.imag + z2.imag
return Complex(real, imag)
def main():
n = int(input("Enter the number of complex numbers: "))
total = Complex(0, 0)
for i in range(n):
real = float(input("Enter the real part of complex number {}: ".format(i+1)))
imag = float(input("Enter the imaginary part of complex number {}: ".format(i+1)))
z = Complex(real, imag)
total = add_complex(total, z)
print("The sum of {} complex numbers is: {} + {}i".format(n, total.real, total.imag))
if name == " main ":
main()
Prof Ramzeela 2022-2023 CSE DEPT PACE
Introduction to Python Programming lab manual
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):
self.name = name
self.usn = usn
self.marks = [0,0,0]
self.total = 0
self.percentage = 0.0
def getMarks(self):
self.marks[0] = int(input("Enter marks in subject 1: "))
self.marks[1] = int(input("Enter marks in subject 2: "))
self.marks[2] = int(input("Enter marks in subject 3: "))
def display(self):
self.total = sum(self.marks)
self.percentage = self.total/3
print("Name: ", self.name)
print("USN: ", self.usn)
print("Marks in subject 1: ", self.marks[0])
print("Marks in subject 2: ", self.marks[1])
print("Marks in subject 3: ", self.marks[2])
print("Total: ", self.total)
print("Percentage: ", self.percentage)
def main():
name = input("Enter name: ")
usn = input("Enter USN: ")
s = Student(name, usn)
Prof Ramzeela 2022-2023 CSE DEPT PACE
Introduction to Python Programming lab manual
s.getMarks()
s.display()
if name == " main ":
main()
Prof Ramzeela 2022-2023 CSE DEPT PACE