0% found this document useful (0 votes)
32 views

Python Lab Manual 1st Year

The document is a laboratory manual for an 'Introduction to Python Programming' course at Atria Institute of Technology for the academic year 2024-2025. It outlines the course structure, including the course code, teaching hours, and a series of programming experiments that students are required to complete, covering various Python programming concepts. Each experiment includes specific tasks such as reading user input, calculating statistics, and file handling, along with example code snippets.

Uploaded by

pratoshchandru
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)
32 views

Python Lab Manual 1st Year

The document is a laboratory manual for an 'Introduction to Python Programming' course at Atria Institute of Technology for the academic year 2024-2025. It outlines the course structure, including the course code, teaching hours, and a series of programming experiments that students are required to complete, covering various Python programming concepts. Each experiment includes specific tasks such as reading user input, calculating statistics, and file handling, along with example code snippets.

Uploaded by

pratoshchandru
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/ 17

DEPARTMENT OF COMPUTER SCIENCE &

ENGINEERING

INTRODUCTION TO PYTHON PROGRAMMING


LABORATORY

2024-2025

ATRIA INSTITUTE OF TECHNOLOGY


Adjacent to Bangalore Baptist HospitalHebbal Bengaluru-560024
Python Lab Manual BIPPB105/205

Title of the Course: Introduction to Python Programming Semester 1

Course Code BIPPB105 CIE Marks 50

Teaching Hours/Week (L:T:P: S) 2:0:2 SEE Marks 50

Total Hours of Pedagogy 40 hours Theory + 8-10 Lab slots Total Marks 100

Credits 03 Exam Hours 3

Examination nature (SEE) Theory

Sl. No Experiments

a.Develop a program to read the student details like Name, USN, and Marks in three
1
subjects Display the student details, total marks and percentage 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.

a. Develop a program to generate Fibonacci sequence of length (N). Read N from the
2
console.
b. Write a function to calculate factorial of a number. Develop a program to compute
binomial coefficient (Given N and R).

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

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

Develop a program to rint 10 most frequently appearing words in a text file. [Hint:
5
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].
Develop a program to sort the contents of a text file and write the sorted contents into
6
a separate text file. [Hint: Use string methods strip (), len (), list methods sort(),
append(), and file methods open(), readlines(), and write()].

Develop a program to backing Up a given Folder (Folder in a current working


7
directory) into a ZIP File by using relevant modules and suitable methods.

Write a function named DivExp which takes TWO parameters a, b and returns a value
8
c (c=a/b). Write suitable assertion for a>0 in function DivExp and raise an exception

Dept Of CS&E,AIT P a g e 2 | 17
Python Lab Manual BIPPB105/205

for when b=0. Develop a suitable program which reads two values from the console and
calls a function DivExp.

Define a function which takes TWO objects representing complex numbers and
9
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) 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 get
Marks() method to read marks into the list, and display() method to display the score
card details.

Dept Of CS&E,AIT P a g e 3 | 17
Python Lab Manual BIPPB105/205

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 percentage with suitable messages.

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("Name:",stName)
print("USN:",stUSN)
print("Marks 1:",stMarks1)
print("Marks 2:",stMarks2)
print("Marks 3:",stMarks3)
print("Total:",stMarks1+stMarks2+stMarks3)
print("Percentage:","%2f"%((stMarks1+stMarks2+stMarks3)/3))
print("-------------------------------------------------------")

Output:

Dept Of CS&E,AIT P a g e 4 | 17
Python Lab Manual BIPPB105/205

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

from datetime import date


perName = input("Enter the name of the person : ")
perDOB = int(input("Enter his year of birth : "))
curYear = date.today().year
#Returns the current local date, .year returns only 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

Dept Of CS&E,AIT P a g e 5 | 17
Python Lab Manual BIPPB105/205

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

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
print()

Output:

Dept Of CS&E,AIT P a g e 6 | 17
Python Lab Manual BIPPB105/205

2.b. Write a function to calculate factorial of a number. Develop a program to compute


binomial coefficient (Given N and R).
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): "))
# Check if R is valid
if r < 0 or r > n:
print("Invalid input: R cannot be negative or greater than N.")
else:
nCr = fact(n) / (fact(r) * fact(n - r))
print(n, 'C', r, " = ", round(nCr), sep="")

Output:

Dept Of CS&E,AIT P a g e 7 | 17
Python Lab Manual BIPPB105/205

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

from math import sqrt


myList = []
num = int(input("Enter the number of elements in your list: "))
# Collecting elements
for i in range(num):
val = int(input("Enter the element: "))
myList.append(val)
print('The length of the list is', len(myList))
print('List Contents:', myList)
# Calculating mean
total = sum(myList)
mean = total / num
# Calculating variance
total_variance = 0
for elem in myList:
total_variance += (elem - mean) ** 2
variance = total_variance / num
# Calculating standard deviation
stdDev = sqrt(variance)
# Output results
print("Mean =", mean)
print("Variance =", variance)
print("Standard Deviation =", "%.2f" % stdDev)

Output:

Dept Of CS&E,AIT P a g e 8 | 17
Python Lab Manual BIPPB105/205

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

num = input("Enter a number : ")


print("The number entered is :", num)
uniqDig = set(num)
for elem in uniqDig:
print(elem, "occurs", num.count(elem), "times")

Output:

Dept Of CS&E,AIT P a g e 9 | 17
Python Lab Manual BIPPB105/205

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

import sys
import string
import os.path
fname = input("Enter the filename : ")
#sample file text.txt is given
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 +
else:
filecontents = filecontents + ' '#replace punctuations and \n with space
wordFreq = {}
wordList = filecontents.split()
#Calculate word Frequency
for word in wordList:
if word not in wordFreq.keys():
wordFreq[word] = 1
else:
wordFreq[word] += 1
#Sort Dictionary based on values in descending order
sortedWordFreq = sorted(wordFreq.items(), key=lambda x:x[1], reverse=True )
#Display 10 most frequently appearing words with their count
print("\n===================================================")
print("10 most frequently appearing words with their count")
print("===================================================")
for i in range(10):
print(sortedWordFreq[i][0], "occurs", sortedWordFreq[i][1], "times")

Output:

Dept Of CS&E,AIT P a g e 10 | 17
Python Lab Manual BIPPB105/205

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

import os
import sys
# Get the filename from the user
fname = input("Enter the filename whose contents are to be sorted: ") # sample file Text.txt
# Check if the file exists
if not os.path.isfile(fname):
print("File", fname, "doesn't exist")
sys.exit(0)
# Read the contents of the file
with open(fname, "r") as infile:
myList = infile.readlines()
# Remove trailing newline characters and create a sorted list
lineList = [line.strip() for line in myList]
lineList.sort() # Sort the list
# Write sorted contents to a new file sorted.txt
with open("sorted.txt", "w") as outfile:
for line in lineList:
outfile.write(line + "\n")
# Check if sorted.txt was created and display its contents
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("==========================================================")

with open("sorted.txt", "r") as rdFile:


for line in rdFile:
print(line, end="")

Output:

Dept Of CS&E,AIT P a g e 11 | 17
Python Lab Manual BIPPB105/205

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

Output:

Dept Of CS&E,AIT P a g e 12 | 17
Python Lab Manual BIPPB105/205

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.

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:

Dept Of CS&E,AIT P a g e 13 | 17
Python Lab Manual BIPPB105/205

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) complex numbers and to
compute the addition of N complex numbers.
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 imaginary part: ")) # Fixed prompt text
def showComplex(self):
print('(', self.realp, ') + i(', self.imagp, ')', sep="") # Fixed quotes
def addComplex(self, c2):
c3 = Complex()
c3.realp = self.realp + c2.realp
c3.imagp = self.imagp + c2.imagp
return c3
def add2Complex(a, b):
return a.addComplex(b)
def main():
# Create two complex numbers using the constructor
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 (number of complex numbers): "))

for i in range(num):
print("Object", i + 1)
obj = Complex()
obj.readComplex()
compList.append(obj)
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()
# Entry point of the program
if __name__ == "__main__":
main()

Dept Of CS&E,AIT P a g e 14 | 17
Python Lab Manual BIPPB105/205

Output:

Dept Of CS&E,AIT P a g e 15 | 17
Python Lab Manual BIPPB105/205

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 get Marks() method to read marks into the list,
and display() method to display the score card details.

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 %12s %8s %8s %8s %8s %12s" % ("NAME", "USN", "MARKS1", "MARKS2",
"MARKS3", "TOTAL", "PERCENTAGE"))
print(spcstr)
print("%15s %12s %8d %8d %8d %8d %12.2f" % (self.name, self.usn, self.score[0], self.score[1],
self.score[2], self.score[3], percentage))
print(spcstr)
def main():
s1 = Student()
s1.getMarks()
s1.display()
if __name__ == "__main__":
main()

Dept Of CS&E,AIT P a g e 16 | 17
Python Lab Manual BIPPB105/205

Output:

Dept Of CS&E,AIT P a g e 17 | 17

You might also like