PYTHON LAB MANUAL : PART I

Dr. Thyagaraju G S and  Ms.Palguni G T

Laboratory Program 1A:  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.

Source Code:

def calculate_percentage(total_marks):
    return (total_marks / (3*max_marks)) * 100

def display_results(name, usn, marks):
    total_marks = sum(marks)
    percentage = calculate_percentage(total_marks)

    print("\nStudent Details:")
    print("Name:", name)
    print("USN:", usn)

    print("\nMarks:")
    print("Subject 1:", marks[0])
    print("Subject 2:", marks[1])
    print("Subject 3:", marks[2])

    print("\nTotal Marks:", total_marks)
    print("Percentage:", percentage, "%")

# Getting input from the user
name = input("Enter student name: ")
usn = input("Enter USN: ")
max_marks = int (input("Enter the max_marks (25/50/100/Any max):"))
marks = []

# Reading marks for three subjects
for i in range(3):
    subject_marks = float(input("Enter marks for subject {0} per {1}: ".format(i+1,max_marks)))
    marks.append(subject_marks)

# Displaying the results
display_results(name, usn, marks)

Sample Output:

Enter student name: Palguni
Enter USN: SDM12345
Enter the max_marks (25/50/100/Any max):25
Enter marks for subject 1 per 25: 21
Enter marks for subject 2 per 25: 22
Enter marks for subject 3 per 25: 23

Student Details:
Name: Palguni
USN: SDM12345

Marks:
Subject 1: 21.0
Subject 2: 22.0
Subject 3: 23.0

Total Marks: 66.0
Percentage: 88.0 %

Laboratory Program 1B:  Develop a program to read the name and year of birth of a person. Display whether the person is a senior citizen or not.

Source Code:

def is_senior_citizen(year_of_birth):
    current_year = 2023
    age = current_year - year_of_birth
    return age >= 60

# Getting input from the user
name = input("Enter your name: ")
year_of_birth = int(input("Enter your year of birth: "))

# Checking if the person is a senior citizen
if is_senior_citizen(year_of_birth):
    print(name, "is a senior citizen.")
else:
    print(name, "is not a senior citizen.")

Sample Output:

Enter your name: Thyagaraju 
Enter your year of birth: 1975
Thyagaraju  is not a senior citizen.

Laboratory Program 2A:  Develop a program to generate Fibonacci sequence of length (N). Read N from the console.

Source Code:

# Program to display the Fibonacci sequence up to N
N = int(input("Enter the length of the sequence "))
# first two terms
t1, t2 = 0, 1
count = 1
# check if the number of terms is valid
if N <= 0:
   print("Please enter a positive integer")
# if there is only one term, return t1
elif N == 1:
   print("Fibonacci sequence upto ",N,": ",end=' ')
   print(n1)
# generate fibonacci sequence
else:
   print("Fibonacci sequence: ")
   while count <= N:
       print(t1,end=' ')
       nexterm = t1 + t2
       # update values
       t1 = t2
       t2 = nexterm
       count += 1

Sample Output:

Enter the length of the sequence 10
Fibonacci sequence: 
0 1 1 2 3 5 8 13 21 34 

Laboratory Program 2B:  Write a function to calculate factorial of a number. Develop a program to compute binomial
coefficient (Given N and R).

Source Code:

# definition 
def fact(N):
    if N == 0:
        return 1
    res = 1
    for i in range(2, N+1):
        res = res * i
    return res

def NCR(N, R):
     return (fact(N)/(fact(R)*fact(N - R)))

print("Please note N must be greater than R")
N=int(input("Enter the value of N: "))
R=int(input("Enter the value of R: "))
print("The Binomial coefficient of {0}C{1} = {2} ".format(N,R,NCR(N,R)))

Sample Output:

Please note N must be greater than R
Enter the value of N: 7
Enter the value of R: 3
The Binomial coefficient of 7C3 = 35.0 

Laboratory Program 3:  Read N numbers from the console and create a list. Develop a program to print mean, variance and standard deviation with suitable messages.

Source Code:

import math
list_num = list()
N = int(input(("Enter the value of N: ")))
print("Enter {0} numbers".format(N))
for i in range(1,N+1):
    num = int(input())
    list_num.append(num)
print("The entered list of numbers is : ",list_num)

# Finding sum of numbers in list
sum = 0
for num in list_num:
    sum = sum + num
print("The sum of numbers in the list is : ",sum)

# To find the mean of numbers in list
mean = sum/len(list_num)
print("Mean of numbers in the list is : ",mean)

# To find variance of numbers in list 
sum_var = 0
for num in list_num:
    sum_var = sum_var + (num -mean)**2
variance = sum_var/N
print("Variance of numbers in the list is : ",variance)

# To find the standard deviation of numbers in list
std = math.sqrt(variance)
print("The standard deviation of numbers in list is : ",std)

Sample Output:

Enter the value of N: 10
Enter 10 numbers
2
3
7
4
6
5
3
8
9
7
The entered list of numbers is :  [2, 3, 7, 4, 6, 5, 3, 8, 9, 7]
The sum of numbers in the list is :  54
Mean of numbers in the list is :  5.4
Variance of numbers in the list is :  5.040000000000001
The standard deviation of numbers in list is :  2.244994432064365

Laboratory Program 4:  Read a multi-digit number (as chars) from the console. Develop a program to print the frequency of each digit with suitable message.

Source Code:

number=int(input("Enter any Multidigit Number : "))
print("Digit\tFrequency")
for i in range(0,10):
    count=0;
    temp=number;
    while temp>0:
        digit=temp%10
        if digit==i:
            count=count+1
        temp=temp//10;
    if count>0:
        print(i,"\t",count)

Sample Output:

Enter any Multidigit Number : 223356789
Digit	Frequency
2 	 2
3 	 2
5 	 1
6 	 1
7 	 1
8 	 1
9 	 1

Laboratory Program 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]

.

Source Code:

from collections import OrderedDict
import numpy as np
import itertools
text = open("spamXY.txt")

def sort_dict_by_value(d, reverse = False):
    return dict(sorted(d.items(), key = lambda x: x[1], reverse = reverse))

# Create an empty dictionary
d = dict()
  
# Loop through each line of the file
for line in text:
    # Remove the leading spaces and newline character
    line = line.strip()
  
    # Convert the characters in line to
    # lowercase to avoid case mismatch
    line = line.lower()
  
    # Split the line into words
    words = line.split(" ")
    
    # To eliminate  delimiters.
    for word in words:
        words.remove(word)
        word = word.replace(".","")
        word = word.replace(",","")
        word = word.replace(":","")
        word = word.replace(";","")
        word = word.replace("!","")
        word = word.replace("*","")
        words.append(word)                    
  
    # Iterate over each word in line
    for word in words:
        # Check if the word is already in dictionary
        if word in d:
            # Increment count of word by 1
            d[word] = d[word] + 1
        else:
            # Add the word to dictionary with count 1
            d[word] = 1
print("\n Sorted dictionary elements by frequency [Descending order]:\n")
d1 =sort_dict_by_value(d, True)
print(d1)
print("\n")

N= int(input("Enter the number of top frequency words to be displayed: \n"))
print("\nThe {0} most frequently appearing words are : \n".format(N))
out = dict(itertools.islice(d1.items(),N))
for i in out:
    print(i)

Input file

Sample Output:

Sorted dictionary elements by frequency [Descending order]:

{'quantum': 6, 'computer': 5, 'and': 5, 'a': 4, 'of': 3, 'the': 3, 'is': 2, 'physical': 2, 'classical': 2, 'could': 2, 'in': 2, 'exploits': 1, 'mechanical': 1, 'phenomena': 1, 'that': 1, 'small': 1, 'exhibits': 1, 'particles': 1, 'waves,': 1, 'scales': 1, 'properties': 1, 'matter': 1, 'at': 1, 'both': 1, 'leverages': 1, 'behavior': 1, 'specialized': 1, 'this': 1, 'hardware': 1, 'using': 1, 'computing': 1, 'physics': 1, 'explain': 1, 'operation': 1, 'these': 1, 'devices,': 1, 'cannot': 1, 'some': 1, 'exponentially': 1, 'than': 1, 'calculations': 1, 'any': 1, 'perform': 1, 'scalable': 1, 'faster': 1, 'modern': 1, 'particular': 1, 'break': 1, 'large-scale': 1, 'encryption': 1, 'physicists': 1, 'performing': 1, 'simulations;': 1, 'schemes': 1, 'widely-used': 1, 'aid': 1, 'state': 1, 'largely': 1, 'however': 1, 'still': 1, 'impractical': 1, 'art': 1, 'current': 1, 'experimental': 1}

Enter the number of top frequency words to be displayed: 
10

The 10 most frequently appearing words are : 

quantum
computer
and
a
of
the
is
physical
classical
could

Laboratory Program 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()].

Source Code:

infile = open("spamXY.txt", "r")
words = []
for line in infile:
    line = line.strip()
    line = line.lower()
    temp = line.split()
    for word in temp:
        temp.remove(word)
        word = word.replace(".","")
        word = word.replace(",","")
        word = word.replace(":","")
        word = word.replace(";","")
        word = word.replace("!","")
        word = word.replace("*","")
        word = word.replace(" ","")
        temp.append(word)
    for i in temp:
        words.append(i)
infile.close()
words.sort()
print("Sorted words : ")
print(words)
# writing the sorted words into result.txt
outfile = open("result.txt", "w")
for i in words:
    outfile.write(i)
    outfile.write("\n")
outfile.close()

Sample Output:

Sorted words : 
['a', 'a', 'a', 'a', 'aid', 'and', 'and', 'and', 'and', 'and', 'any', 'art', 'at', 'behavior', 'both', 'break', 'calculations', 'cannot', 'classical', 'classical', 'computer', 'computer', 'computer', 'computer', 'computer', 'computing', 'could', 'could', 'current', 'devices,', 'encryption', 'exhibits', 'experimental', 'explain', 'exploits', 'exponentially', 'faster', 'hardware', 'however', 'impractical', 'in', 'in', 'is', 'is', 'large-scale', 'largely', 'leverages', 'matter', 'mechanical', 'modern', 'of', 'of', 'of', 'operation', 'particles', 'particular', 'perform', 'performing', 'phenomena', 'physical', 'physical', 'physicists', 'physics', 'properties', 'quantum', 'quantum', 'quantum', 'quantum', 'quantum', 'quantum', 'scalable', 'scales', 'schemes', 'simulations', 'small', 'some', 'specialized', 'state', 'still', 'than', 'that', 'the', 'the', 'the', 'these', 'this', 'using', 'waves', 'widely-used']

Output file :

Laboratory Program 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.

Source Code:

import zipfile, os
folder = input("Enter the folder name in the current working directory : ")
folder = os.path.abspath(folder) # make sure folder is absolute
number = 1
while True:
    zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
    if not os.path.exists(zipFilename):
        break
    number = number + 1
# Create the zip file.
print('Creating %s...' % (zipFilename))
backupZip = zipfile.ZipFile(zipFilename, 'w')
# Walk the entire folder tree and compress the files in each folder.
for foldername, subfolders, filenames in os.walk(folder):
    print('Adding files in %s...' % (foldername))
    # Add the current folder to the ZIP file.
    backupZip.write(foldername)
    # Add all the files in this folder to the ZIP file.
    for filename in filenames:
        if filename.startswith(os.path.basename(folder) + '_') and filename.endswith('.zip'):
            continue # don't backup the backup ZIP files
        backupZip.write(os.path.join(foldername, filename))
backupZip.close()
print('Done.')

Sample Output:

Enter the folder name in the current working directory : cats
Creating cats_1.zip...
Adding files in C:\Users\thyagu\18CS55\cats...
Done.

Compressed file in a given directory :

Laboratory Program 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.

Source Code:

def DivExp(a,b):
    assert a>0,"a must be > 0"
    if b == 0:  
        raise ZeroDivisionError;  
    else: c = a/b
    return c

a = int(input("Enter the value of a :"))  
b = int(input("Enter the value of b :"))
r = DivExp(a,b)
print("The value of {0}/{1} = {2}".format(a,b,r))

Sample Output1 :

Enter the value of a :3
Enter the value of b :2
The value of 3/2 = 1.5

Sample Output 2 :

Sample Output3:

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

Source Code:

# Function to add two complex numbers 
def addComp(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
    return temp;

# Class to represent a Complex Number
class Complex:
    def __init__(self, tempReal, tempImaginary):  
        self.real = tempReal;
        self.imaginary = tempImaginary;

# variable csum for Storing the sum of complex numbers
csum = Complex(0, 0) # inital value of csum set to 0,0
n = int(input("Enter the value of n : "))
for i in range(1,n+1):
    realPart = int(input("Enter the Real Part of complex number {0}:".format(i)))
    imgPart  = int(input("Enter the Imaginary Part of complex number {0}:".format(i)))  
    c = Complex(realPart,imgPart)
    # calling addComp() method
    csum = addComp(csum,c);
    # printing the sum
print("Sum of {0} complex numbers is :".format(n))
print(csum.real, "+i*"+ str(csum.imaginary))

Sample Output:

Enter the value of n : 3
Enter the Real Part of complex number 1:2
Enter the Imaginary Part of complex number 1:3
Enter the Real Part of complex number 2:4
Enter the Imaginary Part of complex number 2:5
Enter the Real Part of complex number 3:6
Enter the Imaginary Part of complex number 3:7
Sum of 3 complex numbers is :
12 +i*15

Laboratory Program 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.]

Source Code : Approach1 (Single Object at a time)

class Student:
    def __init__(self, name, usn, max_marks):
        self.name = name
        self.usn = usn
        self.max_marks = max_marks
        self.marks = []

    def getMarks(self, m1, m2, m3):
        self.marks.extend([m1, m2, m3])

    def displayData(self):
        print("Name is:", self.name)
        print("USN is:", self.usn)
        print("Marks are:", self.marks)
        print("Total Marks is:", self.total())
        print("Average Marks is:", self.average())
        print("Percentage Marks is:", self.percentage())
        print("\n")

    def total(self):
        return sum(self.marks)

    def average(self):
        return sum(self.marks) / len(self.marks)

    def percentage(self):
        return (sum(self.marks) / (self.max_marks * len(self.marks))) * 100

while True:
    name = input("Enter the name (or 'exit' to quit): ")
    
    if name.lower() == 'exit':
        break
    
    usn = int(input("Enter the usn: "))
    max_marks = int(input("Enter the max_marks (25/50/100/Any max): "))
    m1 = int(input("Enter the marks in the first subject out of {}: ".format(max_marks)))
    m2 = int(input("Enter the marks in the second subject out of {}: ".format(max_marks)))
    m3 = int(input("Enter the marks in the third subject out of {}: ".format(max_marks)))

    student = Student(name, usn, max_marks)
    student.getMarks(m1, m2, m3)
    student.displayData()

Sample Output: for Approach1

Enter the name (or 'exit' to quit): Rahul
Enter the usn: 123
Enter the max_marks (25/50/100/Any max): 25
Enter the marks in the first subject out of 25: 23
Enter the marks in the second subject out of 25: 22
Enter the marks in the third subject out of 25: 24
Name is: Rahul
USN is: 123
Marks are: [23, 22, 24]
Total Marks is: 69
Average Marks is: 23.0
Percentage Marks is: 92.0


Enter the name (or 'exit' to quit): Rohan
Enter the usn: 124
Enter the max_marks (25/50/100/Any max): 25
Enter the marks in the first subject out of 25: 24
Enter the marks in the second subject out of 25: 12
Enter the marks in the third subject out of 25: 12
Name is: Rohan
USN is: 124
Marks are: [24, 12, 12]
Total Marks is: 48
Average Marks is: 16.0
Percentage Marks is: 64.0


Enter the name (or 'exit' to quit): exit

Approach2 : For Multiple Objects at a Time

class Student:
    def __init__(self, name, usn, max_marks):
        self.name = name
        self.usn = usn
        self.max_marks = max_marks
        self.marks = []

    def getMarks(self, m1, m2, m3):
        self.marks.extend([m1, m2, m3])

    def displayData(self):
        print("Name is:", self.name)
        print("USN is:", self.usn)
        print("Marks are:", self.marks)
        print("Total Marks is:", self.total())
        print("Average Marks is:", self.average())
        print("Percentage Marks is:", self.percentage())

    def total(self):
        return sum(self.marks)

    def average(self):
        return sum(self.marks) / len(self.marks)

    def percentage(self):
        return (sum(self.marks) / (self.max_marks * len(self.marks))) * 100

# Create a list to store student objects
students = []

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

# Input details for each student
for _ in range(num_students):
    name = input("Enter the name: ")
    usn = int(input("Enter the usn: "))
    max_marks = int(input("Enter the max_marks (25/50/100/Any max): "))
    m1 = int(input("Enter the marks in the first subject out of {}: ".format(max_marks)))
    m2 = int(input("Enter the marks in the second subject out of {}: ".format(max_marks)))
    m3 = int(input("Enter the marks in the third subject out of {}: ".format(max_marks)))

    # Create a student object and add it to the list
    student = Student(name, usn, max_marks)
    student.getMarks(m1, m2, m3)
    students.append(student)

# Display details for each student
for student in students:
    student.displayData()
    print("\n")

Sample Output :

Enter the number of Students: 2
Enter the name: Pavan
Enter the usn: 123
Enter the max_marks (25/50/100/Any max): 25
Enter the marks in the first subject out of 25: 12
Enter the marks in the second subject out of 25: 12
Enter the marks in the third subject out of 25: 13
Enter the name: Rohan
Enter the usn: 124
Enter the max_marks (25/50/100/Any max): 25
Enter the marks in the first subject out of 25: 13
Enter the marks in the second subject out of 25: 12
Enter the marks in the third subject out of 25: 14
Name is: Pavan
USN is: 123
Marks are: [12, 12, 13]
Total Marks is: 37
Average Marks is: 12.333333333333334
Percentage Marks is: 49.333333333333336


Name is: Rohan
USN is: 124
Marks are: [13, 12, 14]
Total Marks is: 39
Average Marks is: 13.0
Percentage Marks is: 52.0