0% found this document useful (0 votes)
3 views14 pages

Python Lab Manual

The document is a Python lab manual containing various programming exercises. It covers topics such as basic arithmetic operations, Fibonacci sequence generation, list manipulation, statistical calculations, text analysis, and file handling. Additionally, it includes exercises on complex numbers, CSV data processing, student grade tracking, and directory traversal.

Uploaded by

Bhuvan kumar HP
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)
3 views14 pages

Python Lab Manual

The document is a Python lab manual containing various programming exercises. It covers topics such as basic arithmetic operations, Fibonacci sequence generation, list manipulation, statistical calculations, text analysis, and file handling. Additionally, it includes exercises on complex numbers, CSV data processing, student grade tracking, and directory traversal.

Uploaded by

Bhuvan kumar HP
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

PYTHON LAB MANUAL

1. a. Develop a python program to read 2 numbers from the keyboard and perform the basic
arithmetic operations based on the choice. (1-Add, 2-Subtract, 3-Multiply, 4-Divide).
while True:
print("\n---- Simple Calculator ----")
print("1 - Add")
print("2 - Subtract")
print("3 - Multiply")
print("4 - Divide")
print("5 - Exit")
choice = input("Enter your choice (1-5): ")
if choice == '5':
print("Exiting program...")
break
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print("Result =", num1 + num2)
elif choice == '2':
print("Result =", num1 - num2)
elif choice == '3':
print("Result =", num1 * num2)
elif choice == '4':
if num2 != 0:
print("Result =", num1 / num2)
else:
print("Error: Division by zero is not allowed.")
else:
print("Invalid choice. Please select between 1 and 5.")
b. Develop a program to read the name and year of birth of a person. Display whether the person
is asenior citizen or not.

import datetime
name = input("Enter the name of the person: ")
year_of_birth = int(input("Enter the year of birth: "))
current_year = [Link]().year
age = current_year - year_of_birth
print("-" * 20)
print(f"Name: {name}")
print(f"Year of Birth: {year_of_birth}")
print(f"Age: {age}")
if age >= 60:
print("Status: Senior Citizen")
else:
print("Status: Not a Senior Citizen")
print("-" * 20)
2. a. Develop a program to generate Fibonacci sequence of length (N). Read N from the console.

n = int(input("Enter the value of N: "))


a, b = 0, 1
print("Fibonacci Sequence:")
for i in range(n):
print(a, end=" ")
a, b = b, a + b

b. Write a python program to create a list and perform the following operations
• Inserting an element
• Removing an element
• Appending an element
• Displaying the length of the list
• Popping an element
• Clearing the list

my_list = [10, 20, 30, 40]


print("Initial list:", my_list)
my_list.insert(1, 15)
print("After inserting 15 at index 1:", my_list)
my_list.remove(30)
print("After removing 30:", my_list)
my_list.append(50)
print("After appending 50:", my_list)
print("Length of the list:", len(my_list))
popped_element = my_list.pop()
print("Popped element:", popped_element)
print("After popping:", my_list)
my_list.clear()
print("After clearing the list:", my_list)
3. a. Read N numbers from the console and create a list. Develop a program to print mean,
variance and standard deviation with suitable messages.
import math
n = int(input("Enter number of elements: "))
numbers = []
for i in range(n):
num = float(input(f"Enter element {i+1}: "))
[Link](num)
mean = sum(numbers) / n
variance = sum((x - mean) ** 2 for x in numbers) / n
std_deviation = [Link](variance)
print("\nResults:")
print("Numbers:", numbers)
print("Mean =", mean)
print("Variance =", variance)
print("Standard Deviation =", std_deviation)

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

number=input("Enter the number\n")


freq_dict={}
for digit in number:
if digit not in freq_dict:
freq_dict[digit]=1
else:
freq_dict[digit]+=1
for key in sorted(freq_dict.keys()):
print("\n Frequency of digit" + key + " in given number is:"
+str(freq_dict[key]))
4. Develop a program to print 10 most frequently appearing words in a text file. [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.

file = open("[Link]","r")
freq_dict = {}
for line in [Link]():
for word in [Link]():
if word not in freq_dict:
freq_dict[word]=1
else:
freq_dict[word] +=1
[Link]()
freq_words = sorted(freq_dict.items(), key=lambda x:x[1], reverse=True)[:10]
print("Top 10 most occuring words in given file are\n")
for x in freq_words:
print("Word: " + x[0] +" with occurance:" + str(x[1]))
5. Develop a program to read 6 subject marks from the keyboard for a student. Generate a report
that displays the marks from the highest to the lowest score attained by the student. [Read the
marks into a 1-Dimesional array and sort using the Bubble Sort technique].
marks = []
print("Enter marks for 6 subjects:")
for i in range(6):
m = float(input(f"Subject {i+1}: "))
[Link](m)
n = len(marks)
for i in range(n):
for j in range(0, n - i - 1):
if marks[j] < marks[j + 1]: # Swap for descending
marks[j], marks[j + 1] = marks[j + 1], marks[j]
print("\nMarks from Highest to Lowest:")
for mark in marks:
print(mark)
6. 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()].

Read_file=open(“[Link]”, “r”)
words=[]
for line in read_file.readlines():
temp=[Link]()
for word in temp:
word = [Link]()
word = [Link](“\n”)
[Link](word)
read_file.close()
print(len(words))
[Link]()
print(words)
sorted_file=open(“sorted_words.txt”, “w”)
for word in words:
sorted_file.writelines(word)
sorted_file.writelines(“\n”)
sorted_file.close()
7. Develop a function named DivExp which takes TWO parameters a, b, and returns a value c
(c=a/b). Write a suitable assertion for a>0 in the function DivExp and raise an exception for when
b=0. Develop a suitable program that reads two console values and calls the function DivExp.

Def DivExp(a, b):


try:
c=a/b
print©
except ZeroDivisionError:
print(“Error: Denominator cannot be zero/ Cannot divide by zero”)
num1=int(input(“Enter first number:”))
num2=int(input(“Enter second number:”))
DivExp(num1,num2)
8. Define a function that takes TWO objects representing complex numbers and returns a new
complex number with the sum 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):
self.real_part = 0
self.img_part = 0
def display(self):
print(str(self.real_part) + "+" + str(self.img_part) + "i")
def add_complex(c1, c2):
c3 = Complex()
c3.real_part = c1.real_part + c2.real_part
c3.img_part = c1.img_part + c2.img_part
return c3
n = int(input("Enter the number of complex numbers you want to add (>=2)"))
complex_nums = []
for i in range(n):
complex_num = Complex()
print("Complex Number = " + str(i + 1) + ":")
complex_num.real_part = int(input("Enter real part: "))
complex_num.img_part = int(input("Enter imaginary part: "))
print("Entered complex number is:", end="")
complex_num.display()
complex_nums.append(complex_num)
complex_sum = add_complex(complex_nums[0], complex_nums[1])
for i in range(2, n):
complex_sum = add_complex(complex_sum, complex_nums[i])
print("\n")
print("Sum of all the complex number is:", end="")
complex_sum.display()
9. Text Analysis Tool: Build a tool that analyses a paragraph: frequency of each word, longest
word, number of sentences, etc.
import string
from collections import Counter
def analyze_text(text):
cleaned_text = [Link](
[Link]('', '', [Link])
)
words = cleaned_text.lower().split()
word_freq = Counter(words)
longest_word = max(words, key=len) if words else ""
sentence_count = (
[Link]('.') +
[Link]('!') +
[Link]('?')
)

char_count = len([Link](" ", ""))


word_count = len(words)
return {
"Word Frequency": dict(word_freq),
"Longest Word": longest_word,
"Sentence Count": sentence_count,
"Word Count": word_count,
"Character Count": char_count
}
paragraph = "This is a simple test. This test is only a test!"
result = analyze_text(paragraph)
for key, value in [Link]():
print(f"{key}: {value}")
10. Develop Data Summary Generator: Read a CSV file (like COVID data or weather stats),
convert to dictionary form, and allow the user to run summary queries: max, min, average by
column. import csv
Import csv
def read_csv(filename):
data = []
with open(filename, 'r') as file:
reader = [Link](file)

for row in reader:


for key in row:
try:
row[key] = float(row[key])
except:
pass
[Link](row)
return data
def find_max(data, column):
values = [
row[column]
for row in data
if isinstance(row[column], (int, float))
]
return max(values)
def find_min(data, column):
values = [
row[column]
for row in data
if isinstance(row[column], (int, float))
]
return min(values)
def find_average(data, column):
values = [
row[column]
for row in data
if isinstance(row[column], (int, float))
]
return sum(values) / len(values)
filename = input("Enter CSV file name: ")
data = read_csv(filename)
print("\nColumns available:")
print(data[0].keys())
column = input("\nEnter column name: ")
print("\nChoose operation:")
print("1. Maximum")
print("2. Minimum")
print("3. Average")
choice = input("Enter choice (1/2/3): ")
if choice == '1':
print("Maximum value:", find_max(data, column))
elif choice == '2':
print("Minimum value:", find_min(data, column))
elif choice == '3':
print("Average value:", find_average(data, column))
else:
print("Invalid choice")
11. Develop Student Grade Tracker: Accept multiple students’ names and marks. Store them in a
list of tuples or dictionaries. Display summary reports (average, topper, etc.).
# Student Grade Tracker

students = {}

n = int(input("Enter number of students: "))

for i in range(n):
name = input("Enter student name: ")
marks = float(input("Enter marks: "))
students[name] = marks

# Average Marks
average = sum([Link]()) / len(students)

# Topper
topper = max(students, key=[Link])

print("\n----- Student Report -----")

print("\nStudent Marks:")
for name, marks in [Link]():
print(name, ":", marks)

print("\nAverage Marks =", average)

print("Topper =", topper)


print("Topper Marks =", students[topper])
12. Develop a program to display contents of a folder recursively (Directory) having sub-folders
and files.
import os

path = input("Enter folder path: ")

for root, dirs, files in [Link](path):

print("\nDirectory:", root)

for d in dirs:
print("Folder :", d)

for f in files:
name, ext = [Link](f)

if ext == "":
ext = "No Extension"

print("File :", f, " Type :", ext)

To create a folders having sub-folders:


mkdir Testfolder
mkdir Testfolder/documents
mkdir Testfolder/images
touch Testfolder/[Link]
touch Testfolder/[Link]
touch Testfolder/documents/[Link]
touch testfolder/images/[Link]
gedit [Link]
python3 [Link]

You might also like