0% found this document useful (0 votes)
8 views30 pages

lab manual- python updates on 27th dec 2024

The document is a lab manual for an 'Introduction to Python Programming' course, detailing various programming experiments and objectives. It includes tasks such as developing programs for student details, Fibonacci sequences, statistical calculations, digit frequency, word frequency in files, and file sorting. Each task is accompanied by programming code examples and expected outputs.

Uploaded by

Sasi.b. Kumar
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)
8 views30 pages

lab manual- python updates on 27th dec 2024

The document is a lab manual for an 'Introduction to Python Programming' course, detailing various programming experiments and objectives. It includes tasks such as developing programs for student details, Fibonacci sequences, statistical calculations, digit frequency, word frequency in files, and file sorting. Each task is accompanied by programming code examples and expected outputs.

Uploaded by

Sasi.b. Kumar
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/ 30

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
Practical Component

Sl. No. Experiments for Conduction

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.

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.

b) Write a function to calculate the factorial of a number. Develop a


program to compute binomial coefficient (Given N and R).

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. Read a multi-digit number (as chars) from the console. Develop a


program to print the frequency of each digit with a suitable message.

5. [Hint: Use a dictionary with distinct words and their frequency of


occurrences. Sort the dictionary in the reverse order of frequency and
display the dictionary slice of the first 10 items]

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

8. Write a function named DivExp which takes TWO parameters a, b


and returns the value of c, where 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. Define a function which takes TWO objects representing complex
numbers and returns new complex number with an addition of
two complex numbers. Define a suitable class ‘Complex’ to
represent the complex number. Develop a program to read N (N

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

>=2) complex numbers and to compute the addition of N


complex numbers.
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.]

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

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
=========================

5
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.

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:

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

7
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

8
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

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:

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

10
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

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:

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

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)

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

14
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("===================================================")

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)

infile = open(fname, "r")

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

#Remove trailing \n characters


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

lineList.sort()

17
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.

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

# Load the Excel file


file_path = 'your_excel_file.xlsx' # replace with your file path
df = pd.read_excel(file_path)

# 1. Reading the first 5 rows of all columns


print("First 5 rows of all columns:")
print(df.head())

# 2. Appending a new row


new_row = {'Column1': 'Value1', 'Column2': 'Value2', 'Column3': 'Value3'} # replace with
your column names and values
df = df.append(new_row, ignore_index=True)

# 2. Appending a new column


df['NewColumn'] = 'DefaultValue' # add a new column with a default value

# 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

# 4. Performing aggregate functions


print("Sum of each column:")
print(df.sum(numeric_only=True))

print("Mean of each column:")


print(df.mean(numeric_only=True))

print("Count of each column:")


print(df.count())

# Save the modified DataFrame back to Excel


df.to_excel('modified_excel_file.xlsx', index=False) # replace with your desired file path

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

Sum of each column:


Column1 115
Column2 145
Column3 175
dtype: int64

Mean of each column:

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

Column1 23.0
Column2 29.0
Column3 35.0
dtype: float64

Count of each column:


Column1 5
Column2 5
Column3 5
dtype: int64

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

val1 = int(input("Enter a value for a : "))


val2 = int(input("Enter a value for b : "))

val3 = DivExp(val1, val2)

print(val1, "/", val2, "=", val3)

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;

# Defining addComp() method


# for adding two complex number
def addComp(self, C1, C2):

# creating temporary variable


temp=Complex(0, 0)

# adding real part of complex numbers


temp.real = C1.real + C2.real;

# adding Imaginary part of complex numbers


temp.imaginary = C1.imaginary + C2.imaginary;

# returning the sum

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

return temp;

# Driver code
if __name__=='__main__':

# First Complex number


C1 = Complex(3, 2);

# printing first complex number


print("Complex number 1 :", C1.real, "+ i" + str(C1.imaginary))

# Second Complex number


C2 = Complex(9, 5);

# printing second complex number


print("Complex number 2 :", C2.real, "+ i" + str(C2.imaginary))

# for Storing the sum


C3 = Complex(0, 0)

# calling addComp() method


C3 = C3.addComp(C1, C2);

# printing the sum


print("Sum of complex number :", C3.real, "+ i"+ str(C3.imaginary))

# This code is contributed by rutvik_56. main()


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

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

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

Entered Complex numbers are :


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

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

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

# Main program to handle multiple students and display in a table


def main():
students = [] # List to store all student objects

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

num_students = int(input("Enter the number of students: "))

for _ in range(num_students):
print("\nEnter details for a new student:")
name = input("Enter student's name: ")
usn = input("Enter student's USN: ")

# Create a Student object


student = Student(name, usn)

# Get marks for the student


student.getMarks()

# Append the student object to the list


students.append(student)

# Display the table


print("\n----------------------------------------------------------------------------")
print(f"{'Name':<20} {'USN':<15} {'Marks':<20} {'Total':<10} {'Percentage':<10}")
print("------------------------------------------------------------------------------")

for student in students:


total = student.calculateTotal()
percentage = student.calculatePercentage()
marks = ', '.join([str(mark) for mark in student.marks]) # Format marks list as a string

# Print the student details in a row of the table


print(f"{student.name:<20} {student.usn:<15} {marks:<20} {total:<10}
{percentage:<10.2f}%")

print("---------------------------------------------------------------------------------")

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

# Run the program


main()
Output:
Enter the number of students: 2

Enter details for a new student:


Enter student's name: John Doe
Enter student's USN: 1RR22MC002
Enter marks for Subject 1: 85
Enter marks for Subject 2: 90
Enter marks for Subject 3: 88

Enter details for a new student:


Enter student's name: Jane Smith
Enter student's USN: 1RR22MC002
Enter marks for Subject 1: 75
Enter marks for Subject 2: 80
Enter marks for Subject 3: 70

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

You might also like