0% found this document useful (0 votes)
0 views28 pages

Lab Manual - Python

The document is a lab manual for an 'Introduction to Python Programming' course, detailing various programming tasks and exercises. It includes instructions for developing programs related to student details, Fibonacci sequences, factorials, statistical calculations, and file operations. Each section outlines objectives, programming code, and example outputs for clarity.

Uploaded by

yyyt59983
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views28 pages

Lab Manual - Python

The document is a lab manual for an 'Introduction to Python Programming' course, detailing various programming tasks and exercises. It includes instructions for developing programs related to student details, Fibonacci sequences, factorials, statistical calculations, and file operations. Each section outlines objectives, programming code, and example outputs for clarity.

Uploaded by

yyyt59983
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252

Lab Manual
Course Title: Introduction to Python Programming
Couse Code: BPLCK152/BPLCK252

1
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252

Lab Programme
Question Programme Page No.

Question 01- a . Student Details 3


b. Senior Citizen Check 5
Question 02 – a. Fibonacci Sequence 6
b. Factorial & Binomial Coefficient 7
Question 03 – Mean, Variance and Standard Deviation 9
Question 04 – Digit Frequency 11

Question 05 – Word Frequency in a File 13


Question 06 – Sort File Contents 16
Question 07 – Backup Directory into Zip Archive 19
Question 08 – Assertions and Exceptions Demo 21
Question 09 – Complex Class Demo 23
Question 10 – Student Class Demo 27

2
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252

Question 1
a. Student Details
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.
Objective:
• 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.
Programming Code:
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 13 19:53:03 2024
@author: profe
"""
stName = input("Enter the name of the student : ")
stUSN = input("Enter the USN of the student : ")
stMarks1 = int(input("Enter marks in Subject 1 : "))
stMarks2 = int(input("Enter marks in Subject 2 : "))
stMarks3 = int(input("Enter marks in Subject 3 : "))
print("Student Details\n=========================")
print("%12s"%("Name :"), stName)
print("%12s"%("USN :"), stUSN)
print("%12s"%("Marks 1 :"), stMarks1)
print("%12s"%("Marks 2 :"), stMarks2)
print("%12s"%("Marks 3 :"), stMarks3)
print("%12s"%("Total :"), stMarks1+stMarks2+stMarks3)
print("%12s"%("Percent :"), "%.2f"%((stMarks1+stMarks2+stMarks3)/3))
print("=========================")
output:
putta:~/.../Programs$ python3 01AStudDetails.py

3
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252

Enter the name of the student : Ramesh


Enter the USN of the student : RR1CS007
Enter marks in Subject 1 : 34
Enter marks in Subject 2 : 67
Enter marks in Subject 3 : 78
Student Details
=========================
Name : Ramesh
USN : RR1CS007
Marks 1 : 34
Marks 2 : 67
Marks 3 : 78
Total : 179
Percent : 59.67
=========================

4
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252

b. Senior Citizen Check


Develop a program to read the name and year of birth of a person. Display whether the
person is a senior citizen or not.
Objective:
Develop a program to read the name and year of birth of a person. Display whether the
person is a senior citizen or not.
Programming Code:

from datetime import date

perName = input("Enter the name of the person : ")


perDOB = int(input("Enter his year of birth : "))

curYear = date.today().year
perAge = curYear - perDOB

if (perAge > 60):


print(perName, "aged", perAge, "years is a Senior Citizen.")
else:
print(perName, "aged", perAge, "years is not a Senior Citizen.")
Output:
putta:~/.../Programs$ python3 01BChkSnrCitzn.py
Enter the name of the person : Ganesh
Enter his year of birth : 1978
Akbar Khan aged 44 years is not a Senior Citizen.
putta:~/.../Programs$ python3 01BChkSnrCitzn.py
Enter the name of the person : Danial
Enter his year of birth : 1957
George Best aged 65 years is a Senior Citizen.

5
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252

Question 2
a. Fibonacci Sequence
Develop a program to generate Fibonacci sequence of length (N). Read N from the console.
Objective:
Develop a program to generate Fibonacci sequence of length (N). Read N from the console.
Programming Code:

num = int(input("Enter the Fibonacci sequence length to be generated : "))

firstTerm = 0
secondTerm = 1
print("The Fibonacci series with", num, "terms is :")
print(firstTerm, secondTerm, end=" ")
for i in range(2,num):
curTerm = firstTerm + secondTerm
print(curTerm, end=" ")
firstTerm = secondTerm
secondTerm = curTerm
Output:
putta:~/.../Programs$ python3 02AFibonacci.py
Enter the Fibonacci sequence length to be generated : 8
The Fibonacci series with 8 terms is :0 1 1 2 3 5 8 13

putta:~/.../Programs$ python3 02AFibonacci.py


Enter the Fibonacci sequence length to be generated : 5
The Fibonacci series with 5 terms is :
01123

6
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252

b. Factorial & Binomial Coefficient


Write a function to calculate factorial of a number. Develop a program to compute binomial
coefficient (Given N and R).
Objective:
Write a function to calculate factorial of a number.
Develop a program to compute binomial coefficient (Given N and R).
Programming Code:
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:
putta:~/.../Programs$ python3 02BFactNCR.py
Enter the value of N : 7
Enter the value of R (R cannot be negative or greater than N): 5
7C5 = 21

Enter the value of N : 5


Enter the value of R (R cannot be negative or greater than N): 5
5C5 = 1

Enter the value of N : 3


Enter the value of R (R cannot be negative or greater than N): 1

7
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252

3C1 = 3

Enter the value of N : 8


Enter the value of R (R cannot be negative or greater than N): 0
8C0 = 1

8
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252

Question 3
Mean, Variance and Standard Deviation
Read N numbers from the console and create a list. Develop a program to print mean,
variance and standard deviation with suitable messages.
Objective:
Read N numbers from the console and create a list. Develop a program to print mean,
variance and
standard deviation with suitable messages.
Programming Code:

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

9
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252

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:
Enter the number of elements in your list : 5
Enter the element : 45
Enter the element : 57
Enter the element : 67
Enter the element : 89
Enter the element : 54
The length of list1 is 5
List Contents [45, 57, 67, 89, 54]
Mean = 62.4
Variance = 226.23999999999995
Standard Deviation = 15.04

10
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252

Question 4
Digit Frequency
Read a multi-digit number (as chars) from the console. Develop a program to print the
frequency of each digit with suitable message.
Objective:
Read a multi-digit number (as chars) from the console.
Develop a program to print the frequency of each digit with suitable message.
Programming Code:

num = input("Enter a number : ")


print("The number entered is :", num)

uniqDig = set(num)
#print(uniqDig)

for elem in uniqDig:


print(elem, "occurs", num.count(elem), "times")
Output:
runfile('E:/Personal Files/ACS/prog/untitled7.py', wdir='E:/Personal Files/ACS/prog')
Enter a number : 66733322
The number entered is : 66733322
7 occurs 1 times
2 occurs 2 times
6 occurs 2 times
3 occurs 3 times

runfile('E:/Personal Files/ACS/prog/untitled7.py', wdir='E:/Personal Files/ACS/prog')


Enter a number : 6677332211
The number entered is : 6677332211
1 occurs 2 times

11
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252

7 occurs 2 times
2 occurs 2 times
3 occurs 2 times
6 occurs 2 times

12
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252

Question 5
Word Frequency in a File
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]
Objective:
Develop a program to print 10 most frequently appearing words in text file.
Programming Code:

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 newline with a space

13
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252

wordFreq = {}

wordList = filecontents.split()

#Calculate word Frequency

for word in wordList:


if word not in wordFreq.keys():
wordFreq[word] = 1
else:
wordFreq[word] += 1

# print(wordFreq)

# for word, frequency in wordFreq.items():


# print(word, "occurs", frequency, "times")

#Sort Dictionary based on values in descending order


sortedWordFreq = sorted(wordFreq.items(), key=lambda x:x[1], reverse=True )

# print(type(sortedWordFreq))

# print(sortedWordFreq)

#Display 10 most frequently appearing words with their count

print("\n===================================================")
print("10 most frequently appearing words with their count")
print("===================================================")

14
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252

for i in range(10):
print(sortedWordFreq[i][0], "occurs", sortedWordFreq[i][1], "times")
Output:
runfile('E:/Personal Files/ACS/prog/Prog4.py', wdir='E:/Personal Files/ACS/prog')
Enter the filename : aboutme.txt

===================================================
10 most frequently appearing words with their count
===================================================
the occurs 8 times
your occurs 7 times
and occurs 6 times
you occurs 4 times
for occurs 4 times
can occurs 3 times
job occurs 3 times
answering occurs 2 times
question occurs 2 times
skills occurs 2 times

15
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252

Question 6
Sort File Contents
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()].
Objective:
Develop a program to sort the contents of a text file and write the sorted contents into a
separate textfile. [Hint: Use string methods strip(), len(), list methods sort(), append(), and
file methods open(),readlines(), and write()].
Programming Code:

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)

infile = open(fname, "r")

myList = infile.readlines()
# print(myList)

#Remove trailing \n characters


lineList = []
for line in myList:
lineList.append(line.strip())

lineList.sort()

16
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252

#Write sorted contents to new file sorted.txt

outfile = open("sorted.txt","w")

for line in lineList:


outfile.write(line + "\n")

infile.close() # Close the input file


outfile.close() # Close the output file

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:
runfile('E:/Personal Files/ACS/prog/Prog5.py', wdir='E:/Personal Files/ACS/prog')
Enter the filename whose contents are to be sorted : aboutme.txt
File containing sorted content sorted.txt created successfully
sorted.txt contains 9 lines
Contents of sorted.txt
====================================================
Connect with the interviewer: Greet the interviewers and thank them for the opportunity.

17
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252

Focus on the job: Avoid summarizing your resume or going into personal details. Instead,
focus on your most recent background, what made you apply for the job, and your top
qualifications.
Keep it brief: Your answer should be around 30 seconds to two minutes long.
Learn more
Practice: Practice your answer so you can deliver it smoothly
Search Labs | AI Overview
Use stories: Share professional anecdotes and stories that illustrate your skills and experience.
When answering the interview question "Tell me about yourself", you can highlight your
relevant skills, experience, and achievements that make you a good fit for the role. You can
also mention your current job responsibilities and how they align with the role. Here are some
tips for answering this question:
…

18
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252

Question 7
Backup Directory into Zip archive
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.
Objective:
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.
Programming Code:

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")

19
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252

Output:
runfile('E:/Personal Files/ACS/prog/prog7.py', wdir='E:/Personal Files/ACS/prog')
Enter Directory name that you want to backup : zipDemo
Archive myZip.zip created successful

20
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252

Question 8
Assertions and Exceptions Demo
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.
Objective:
• Write a function named DivExp which takes TWO parameters a, b and returns a value
c (c=a/b). 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.
Programming Code:

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)


Output:

21
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252

runfile('E:/Personal Files/ACS/prog/prog8.py', wdir='E:/Personal Files/ACS/prog')


Enter a value for a : 5
Enter a value for b : 6
5 / 6 = 0.8333333333333334
runfile('E:/Personal Files/ACS/prog/prog8.py', wdir='E:/Personal Files/ACS/prog')
Enter a value for a : 7
Enter a value for b : 8
7 / 8 = 0.875
runfile('E:/Personal Files/ACS/prog/prog8.py', wdir='E:/Personal Files/ACS/prog')
Enter a value for a : 4
Enter a value for b : 7
4 / 7 = 0.5714285714285714

22
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252

Question 9
Complex Class Demo
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.
Objective:
• 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. By two objects.
Programming Code:
class Complex:
def __init__(self, realp = 0, imagp=0):
self.realp = realp
self.imagp = imagp

def setComplex(self, realp, imagp):


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 addComplex(self, c2):


c3 = Complex()
c3.realp = self.realp + c2.realp
c3.imagp = self.imagp + c2.imagp
return c3

23
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252

def add2Complex(a,b):
c = a.addComplex(b)
return c

def main():
c1 = Complex(3,5)
c2 = Complex(6,4)

print("Complex Number 1")


c1.showComplex()
print("Complex Number 2")
c2.showComplex()

c3 = add2Complex(c1, c2)

print("Sum of two Complex Numbers")


c3.showComplex()

#Addition of N (N >=2) complex numbers

compList = []

num = int(input("\nEnter the value for N : "))

for i in range(num):
print("Object", i+1)
obj = Complex()
obj.readComplex()
compList.append(obj)

24
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252

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:
runfile('E:/Personal Files/ACS/prog/untitled11.py', wdir='E:/Personal Files/ACS/prog')
Complex Number 1
(3)+i(5)
Complex Number 2
(6)+i(4)

Sum of two Complex Numbers


(9)+i(9)
Enter the value for N : 2
Object 1
Enter the real part : 3
Enter the real part : 3
Object 2
Enter the real part : 4
Enter the real part : 5

25
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252

Entered Complex numbers are :


(3)+i(3)
(4)+i(5)

Sum of N complex numbers is (7)+i(8)

26
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252

Question 10
Student Class Demo
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.
Objective:
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.
Programming Code:
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"%"TOTAL","%12s"%("PERCENTAGE"))

27
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252

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:
runfile('E:/Personal Files/ACS/prog/Prog10.py', wdir='E:/Personal Files/ACS/prog')
Enter student Name : rahul
Enter student USN : 1RR22014
Enter marks in Subject 1 : 45
Enter marks in Subject 2 : 4
Enter marks in Subject 3 : 56
==================================================================
SCORE CARD DETAILS
==================================================================
NAME USN MARKS1 MARKS2 MARKS3 TOTAL PERCENTAGE
==================================================================
rahul 1RR22014 45 4 56 105 35.00
==================================================================
************

28

You might also like