lab manual- python updates on 27th dec 2024
lab manual- python updates on 27th dec 2024
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
Practical Component
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
percentages with suitable messages.
3. Read N numbers from the console and create a list. Develop a program
to print mean, variance, and standard deviation with suitable messages.
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. Implement a Python program to perform the following operations
on an Excel spreadsheet:
• • Reading the first 5 rows of all columns
• • Appending a new row / new column
• • Delete row/column
• • To perform aggregate functions
2
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252
3
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
4
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252
5
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252
curYear = date.today().year
perAge = curYear - perDOB
6
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
7
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
8
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252
3C1 = 3
9
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
10
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252
total = 0
for elem in myList:
total += (elem - mean) * (elem - mean)
stdDev = sqrt(variance)
11
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)
12
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
13
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 = ""
14
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("===================================================")
15
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
16
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()
17
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.
18
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:
…
19
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252
Question 7
Implement a Python program to perform the following operations on an Excel
spreadsheet:
• Reading the first 5 rows of all columns
• Appending a new row / new column
• Delete row/column
• To perform aggregate functions
Programming Code:
import pandas as pd
# 3. Deleting a row
df = df.drop(index=0) # deleting the first row (change the index as needed)
# 3. Deleting a column
df = df.drop(columns=['NewColumn']) # deleting the newly added column (change the
column name as needed)
20
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252
Output:
First 5 rows of all columns:
Column1 Column2 Column3
0 10 20 30
1 15 25 35
2 20 30 40
3 25 35 45
4 30 40 50
21
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252
Column1 23.0
Column2 29.0
Column3 35.0
dtype: float64
22
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
23
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252
Output:
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
24
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:
# Constructor to accept
# real and imaginary part
def __init__(self, tempReal, tempImaginary):
self.real = tempReal;
self.imaginary = tempImaginary;
25
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252
return temp;
# Driver code
if __name__=='__main__':
26
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252
Complex Number 1
(3)+i(5)
Complex Number 2
(6)+i(4)
27
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):
self.name = name
self.usn = usn
self.marks = []
def getMarks(self):
for i in range(3):
mark = float(input(f"Enter marks for Subject {i+1}: "))
self.marks.append(mark)
def calculateTotal(self):
return sum(self.marks)
def calculatePercentage(self):
total = self.calculateTotal()
return (total / 300) * 100
28
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252
for _ in range(num_students):
print("\nEnter details for a new student:")
name = input("Enter student's name: ")
usn = input("Enter student's USN: ")
print("---------------------------------------------------------------------------------")
29
Course Title: Introduction to Python Programming Couse Code: BPLCK152/BPLCK252
--------------------------------------------------------------------------------------
Name USN Marks Total Percentage
---------------------------------------------------------------------------------------
John Doe 1RR22MC002 85.0, 90.0, 88.0 263.0 87.67%
Jane Smith 1RR22MC003 75.0, 80.0, 70.0 225.0 75.00%
--------------------------------------------------------------------------------------
************
30