Lab Manual - Python
Lab Manual - Python
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.
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
4
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252
curYear = date.today().year
perAge = curYear - perDOB
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:
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
6
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252
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
7
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252
3C1 = 3
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:
myList = []
for i in range(num):
val = int(input("Enter the element : "))
myList.append(val)
total = 0
for elem in myList:
total += elem
9
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252
total = 0
for elem in myList:
total += (elem - mean) * (elem - mean)
stdDev = sqrt(variance)
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:
uniqDig = set(num)
#print(uniqDig)
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)
filecontents = ""
13
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252
wordFreq = {}
wordList = filecontents.split()
# print(wordFreq)
# print(type(sortedWordFreq))
# print(sortedWordFreq)
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)
myList = infile.readlines()
# print(myList)
lineList.sort()
16
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252
outfile = open("sorted.txt","w")
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
if not os.path.isdir(dirName):
print("Directory", dirName, "doesn't exists")
sys.exit(0)
curDirectory = pathlib.Path(dirName)
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
21
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252
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 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="")
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)
c3 = add2Complex(c1, c2)
compList = []
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
sumObj = Complex()
for obj in compList:
sumObj = add2Complex(sumObj, obj)
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)
25
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252
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