0% found this document useful (0 votes)
25 views11 pages

Python Lab

The document contains a series of Python programming tasks covering various topics such as arithmetic operations, list manipulations, statistical calculations, text analysis, and file handling. Each task includes code snippets that demonstrate how to implement the required functionality, such as reading user input, performing calculations, and displaying results. The document serves as a comprehensive guide for developing basic to intermediate Python applications.

Uploaded by

sahana.br
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views11 pages

Python Lab

The document contains a series of Python programming tasks covering various topics such as arithmetic operations, list manipulations, statistical calculations, text analysis, and file handling. Each task includes code snippets that demonstrate how to implement the required functionality, such as reading user input, performing calculations, and displaying results. The document serves as a comprehensive guide for developing basic to intermediate Python applications.

Uploaded by

sahana.br
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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

# Read two numbers from the user


num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

# Display menu
print("\nChoose an operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")

# Take user choice


choice = int(input("Enter your choice (1-4): "))

# Perform operation based on choice


if choice == 1:
result = num1 + num2
print("Result:", result)

elif choice == 2:
result = num1 - num2
print("Result:", result)

elif choice == 3:
result = num1 * num2
print("Result:", result)

elif choice == 4:
if num2 != 0:
result = num1 / num2
print("Result:", result)
else:
print("Error: Division by zero is not allowed.")

else:
print("Invalid choice! Please select between 1 and 4.")

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

name = input("Enter your name: ")


year_of_birth = int(input("Enter your year of birth: "))
# Get current year
current_year = 2026

# Calculate age
age = current_year - year_of_birth

# Check if senior citizen (age >= 60)


if age >= 60:
print(name, "is a Senior Citizen.")
else:
print(name, "is not a Senior Citizen.")

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

N = int(input("Enter N value: "))


n1, n2 = 0, 1
count = 0
if N <= 0:
print("Please enter a positive integer")
elif
N == 1:
print("Fibonacci sequence upto",N,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < N:
print(n1)
nxt = n1 + n2
n1 = n2
n2 = nxt
count += 1

2b. 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

# Create an empty list


my_list = []

while True:
print("\n--- List Operations Menu ---")
print("1. Insert an element")
print("2. Remove an element")
print("3. Append an element")
print("4. Display length of the list")
print("5. Pop an element")
print("6. Clear the list")
print("7. Display the list")
print("8. Exit")

choice = int(input("Enter your choice (1-8): "))

if choice == 1:
pos = int(input("Enter position: "))
element = input("Enter element: ")
my_list.insert(pos, element)
print("Element inserted.")

elif choice == 2:
element = input("Enter element to remove: ")
if element in my_list:
my_list.remove(element)
print("Element removed.")
else:
print("Element not found.")

elif choice == 3:
element = input("Enter element to append: ")
my_list.append(element)
print("Element appended.")

elif choice == 4:
print("Length of list:", len(my_list))

elif choice == 5:
if my_list:
popped = my_list.pop()
print("Popped element:", popped)
else:
print("List is empty.")

elif choice == 6:
my_list.clear()
print("List cleared.")
elif choice == 7:
print("Current List:", my_list)

elif choice == 8:
print("Exiting program.")
break

else:
print("Invalid choice! Please try again.")

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 N value:"))
Mylist=[]
print("Enter a value")
for i in range(n):
v=int(input())
[Link](v)
lenv=len(Mylist)
if(lenv == 0):
print("List should not be empty")
else:
sumv=sum(Mylist)
meanval = sumv/lenv
temp=0
for i in range(lenv):
temp += ((Mylist[i] - meanval) * (Mylist[i] - meanval))
vari = temp / lenv;
sd = [Link](vari)
print("Mean value: ",meanval)
print("Varience: ",vari)
print("Standard Deviation: ",sd)

3b. Read a multi-digit number (as chars) from the console. Develop a program to print the frequency
of each digit with a suitable message.
str1 = input("Enter a multi-digit number: ")
d = dict()
for c in str1:
if c in [Link]():
d[c] = d[c] + 1
else:
d[c] = 1
for k,v in [Link]():
print("Number ",k," has frequency: ",v)

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.

fname = input('Enter the file name: ')


try:
fhand = open(fname,"r")
counts = dict()
for line in fhand:
words = [Link]()
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
counts=sorted(counts,reverse=True)
print(counts[:11])
except:
print("File can't open")

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

# Read 6 subject marks into a list


marks = []

print("Enter marks for 6 subjects:")


for i in range(6):
m = float(input(f"Enter mark {i+1}: "))
[Link](m)

# Bubble Sort (Descending Order)


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 order
marks[j], marks[j + 1] = marks[j + 1], marks[j]

# Display sorted marks


print("\nMarks in descending order (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
text file. [Hint: Use string methods strip(), len(), list methods sort(), append(), and file methods
open(), readlines(), and write()].

infile = input("Enter input file name: ")


fh_in = open(infile,"r")
data=fh_in.readlines()
lst = []
for i in range(len(data)):
[Link](data[i].strip())
[Link]()
fh_in.close()
outfile=input("Enter output file name: ")
fh_out = open(outfile, "w")
for i in lst:
fh_out.write(i)
fh_out.write("\n")
fh_out.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.

import sys
def DivExp(a,b):
try:
assert a>0, "Expected number should be positive"
assert b!=0, "Can't divide by zero"
c=a/b
return c
except AssertionError as msg:
[Link](msg)
v1=int(input("Enter first number: "))
v2=int(input("Enter second number: "))
res=DivExp(v1,v2)
print(v1,"%",v2," is: ",res)

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,r,i):
[Link] = r
[Link] = i
def addcom(self, other):
return Complex([Link] + [Link], [Link] + [Link])

N=int(input("Enter a number of complex numbers: "))


sum=Complex(0,0)
for i in range(N):
print("\nComplex Number:",i+1)
a=int(input("Enter real part: "))
b=int(input("Enter imaginary part: "))
c=Complex(a,b)
sum=[Link](c)
print("\nAfter Sum:",[Link],"+",[Link],"i")

9. Text Analysis Tool: Build a tool that analyses a paragraph: frequency of each word, longest word,
number of sentences, etc

import string

# Read paragraph input


text = input("Enter a paragraph:\n")

# Convert to lowercase for uniform analysis


text_lower = [Link]()

# Remove punctuation (except sentence delimiters)


translator = [Link]('', '', [Link]('.', '').replace('!', '').replace('?', ''))
clean_text = text_lower.translate(translator)

# Split into words


words = clean_text.split()

# Word frequency
frequency = {}
for word in words:
if word in frequency:
frequency[word] += 1
else:
frequency[word] = 1

# Find longest word


longest_word = ""
for word in words:
if len(word) > len(longest_word):
longest_word = word
# Count sentences
sentence_count = 0
for ch in text:
if ch in '.!?':
sentence_count += 1

# Display results
print("\n--- Text Analysis Report ---")
print("Total words:", len(words))
print("Number of sentences:", sentence_count)
print("Longest word:", longest_word)

print("\nWord Frequency:")
for word, count in [Link]():
print(word, ":", count)

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

# Function to read CSV and convert to list of dictionaries


def read_csv_file(filename):
data = []
try:
with open(filename, 'r') as file:
reader = [Link](file)
for row in reader:
[Link](row)
return data
except FileNotFoundError:
print("File not found!")
return []

# Function to extract numeric column values


def get_column_data(data, column):
values = []
for row in data:
try:
[Link](float(row[column]))
except:
pass # Ignore non-numeric values
return values
# Main program
filename = input("Enter CSV file name (with .csv): ")
data = read_csv_file(filename)

if not data:
exit()

print("\nAvailable columns:", list(data[0].keys()))

while True:
print("\n--- Summary Menu ---")
print("1. Maximum")
print("2. Minimum")
print("3. Average")
print("4. Exit")

choice = int(input("Enter your choice: "))


if choice == 4:
break

column = input("Enter column name: ")

if column not in data[0]:


print("Invalid column name!")
continue

values = get_column_data(data, column)

if not values:
print("No numeric data in this column!")
continue

if choice == 1:
print("Maximum value:", max(values))

elif choice == 2:
print("Minimum value:", min(values))

elif choice == 3:
avg = sum(values) / len(values)
print("Average value:", avg)

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

# Create an empty list to store student data


students = []

# Input number of students


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

# Read student details


for i in range(n):
name = input(f"\nEnter name of student {i+1}: ")
marks = float(input(f"Enter marks of {name}: "))
[Link]({"name": name, "marks": marks})

# Display all student records


print("\n--- Student Records ---")
for s in students:
print(s["name"], ":", s["marks"])

# Calculate average marks


total = sum(s["marks"] for s in students)
average = total / n
print("\nAverage Marks:", average)

# Find topper (highest marks)


topper = max(students, key=lambda x: x["marks"])
print("Topper:", topper["name"], "with", topper["marks"], "marks")

# Find lowest scorer


lowest = min(students, key=lambda x: x["marks"])
print("Lowest Scorer:", lowest["name"], "with", lowest["marks"], "marks")

12. Develop a program to display contents of a folder recursively (Directory) having sub-folders and
files (name and type).

import os

def display_directory(path, level=0):


try:
for item in [Link](path):
full_path = [Link](path, item)

# Indentation for hierarchy


indent = " " * level

if [Link](full_path):
print(f"{indent}[Folder] {item}")
# Recursive call for subfolder
display_directory(full_path, level + 1)
else:
# Get file extension/type
file_type = [Link](item)[1]
print(f"{indent}[File] {item} (Type: {file_type})")

except PermissionError:
print("Permission denied:", path)

# Main program
folder_path = input("Enter folder path: ")

if [Link](folder_path):
print("\nDirectory Structure:\n")
display_directory(folder_path)
else:
print("Invalid path!")

You might also like