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

Python Lab Manual

The document contains multiple programming tasks, including reading student details, calculating Fibonacci sequences, computing binomial coefficients, and analyzing statistics like mean and variance. It also covers file operations such as sorting file contents, backing up folders, and handling exceptions in calculations. Additionally, it involves creating classes for complex numbers and students to manage data and display results effectively.
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)
2 views

Python Lab Manual

The document contains multiple programming tasks, including reading student details, calculating Fibonacci sequences, computing binomial coefficients, and analyzing statistics like mean and variance. It also covers file operations such as sorting file contents, backing up folders, and handling exceptions in calculations. Additionally, it involves creating classes for complex numbers and students to manage data and display results effectively.
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/ 13

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.
# Read student details
name = input("Enter student's name: ")
usn = input("Enter student's USN: ")
# Read marks for three subjects
marks1 = float(input("Enter marks in subject 1: "))
marks2 = float(input("Enter marks in subject 2: "))
marks3 = float(input("Enter marks in subject 3: "))
# Calculate total marks and percentage
total_marks = marks1 + marks2 + marks3
percentage = (total_marks / 300) * 100
# Display student details, total marks, and percentage
print("\n--- Student Details ---")
print("Name:",name)
print("USN:",usn)
print("Marks in Subject 1:",marks1)
print("Marks in Subject 2:",marks2)
print("Marks in Subject 3:",marks1)
print("Total Marks" + str(total_marks) +"out of 300")
print("Percentage:"+ str(percentage)+"%")
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.
# Input: Name and Year of Birth
name = input("Enter your name: ")
year_of_birth = int(input("Enter your year of birth: "))

# Get the current year


import datetime
current_year = datetime.datetime.now().year

# Calculate the age


age = current_year - year_of_birth

# Check if the person is a senior citizen


if age >= 60:
print(name,"you are a senior citizen.")
else:
print(name,"you are not a senior citizen.")
2.a)Develop a program to generate Fibonacci sequence of length (N). Read N from the console.
def generate_fibonacci(N):
# Initialize the sequence with the first two Fibonacci numbers
fibonacci_sequence = [0, 1]

for i in range(2, N):


next_number = fibonacci_sequence[-1] + fibonacci_sequence[-2]
fibonacci_sequence.append(next_number)

return fibonacci_sequence[:N] # Return only the first N numbers

if __name__ == "__main__":
# Read N from the console
N = int(input("Enter the length of the Fibonacci sequence: "))

# Generate the Fibonacci sequence


fibonacci_sequence = generate_fibonacci(N)

# Print the Fibonacci sequence


print("Fibonacci sequence of length", N, "is:")
print(fibonacci_sequence)
2.b)Write a function to calculate factorial of a number. Develop a program to compute binomial
coefficient (Given N and R).
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)

def binomial_coefficient(N, R):


return factorial(N) / (factorial(R) * factorial(N - R))

if __name__ == "__main__":
# Read N and R from the console
N = int(input("Enter the value of N: "))
R = int(input("Enter the value of R: "))

# Compute the binomial coefficient


result = binomial_coefficient(N, R)

# Print the result


print(f"Binomial Coefficient C({N}, {R}) is: {result}")
3. Read N numbers from the console and create a list. Develop a program to print mean, variance and
standard deviation with suitable messages.
import statistics

def main():
# Read N from the console
N = int(input("Enter the number of elements: "))

# Read N numbers from the console and create a list


numbers = []
for i in range(N):
number = float(input(f"Enter number {i+1}: "))
numbers.append(number)

# Calculate mean
mean = statistics.mean(numbers)

# Calculate variance
variance = statistics.variance(numbers)

# Calculate standard deviation


std_deviation = statistics.stdev(numbers)

# Print the results with suitable messages


print(f"The mean of the numbers is: {mean}")
print(f"The variance of the numbers is: {variance}")
print(f"The standard deviation of the numbers is: {std_deviation}")

# Call the main function


if __name__ == "__main__":
main()
4. Read a multi-digit number (as chars) from the console. Develop a program to print the frequency of
each digit with suitable message.
def count_digit_frequency(number):
# Create a dictionary to store the frequency of each digit
digit_frequency = {}

# Initialize the frequency of each digit from 0 to 9 to 0


for digit in '0123456789':
digit_frequency[digit] = 0

# Count the frequency of each digit in the number


for char in number:
if char.isdigit():
digit_frequency[char] += 1

return digit_frequency

if __name__ == "__main__":
# Read a multi-digit number as characters from the console
number = input("Enter a multi-digit number: ")

# Get the frequency of each digit


digit_frequency = count_digit_frequency(number)

# Print the frequency of each digit with a suitable message


for digit, frequency in digit_frequency.items():
print(f"Digit {digit} appears {frequency} times.")
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 re
from collections import Counter

def get_top_n_words(file_path, n=10):


# Read the content of the file
with open(file_path, 'r') as file:
text = file.read()

# Use regular expressions to find all words (considering words as sequences of alphanumeric
characters)
words = re.findall(r'\b\w+\b', text.lower())

# Count the frequency of each word


word_counts = Counter(words)

# Get the n most common words


top_n_words = word_counts.most_common(n)
return top_n_words

if __name__ == "__main__":
# Path to the text file
file_path = 'example.txt' # Replace 'example.txt' with the path to your text file

# Get the top 10 most frequently appearing words


top_words = get_top_n_words(file_path)

# Print the top 10 words with their frequencies


print("The 10 most frequently appearing words are:")
for word, frequency in top_words:
print(f"Word: '{word}', Frequency: {frequency}")
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()].
def sort_file_contents(input_file, output_file):
# Open the input file in read mode
with open(input_file, 'r') as file:
lines = file.readlines() # Read all lines from the file

# Strip newline characters and sort the lines


lines = [line.strip() for line in lines] # Remove any leading/trailing whitespace
lines.sort() # Sort the lines alphabetically

# Open the output file in write mode


with open(output_file, 'w') as file:
for line in lines:
file.write(line + '\n') # Write each sorted line to the output file

if __name__ == "__main__":
# Specify the input and output file paths
input_file = 'input.txt' # Replace with your input file path
output_file = 'sorted_output.txt' # Replace with your desired output file path

# Sort the contents of the input file and write to the output file
sort_file_contents(input_file, output_file)

print(f"Contents of '{input_file}' have been sorted and written to '{output_file}'")


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 shutil
from datetime import datetime

def backup_folder_to_zip(folder_name):
# Get the current working directory
current_dir = os.getcwd()

# Path to the folder to be backed up


folder_path = os.path.join(current_dir, folder_name)

# Create a timestamped name for the ZIP file


timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
zip_filename = f"{folder_name}_backup_{timestamp}.zip"
zip_filepath = os.path.join(current_dir, zip_filename)

# Create a ZIP file backup of the folder


shutil.make_archive(zip_filepath.replace('.zip', ''), 'zip', folder_path)

print(f"Backup of '{folder_name}' folder has been created: {zip_filepath}")

if __name__ == "__main__":
# Folder name to be backed up
folder_name = input("Enter the name of the folder to back up: ")

# Back up the folder into a ZIP file


backup_folder_to_zip(folder_name)
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.
def DivExp(a, b):
# Assert that a is greater than 0
assert a > 0, "Assertion failed: a must be greater than 0"

# Raise an exception if b is 0
if b == 0:
raise ZeroDivisionError("Division by zero is not allowed")

# Perform the division


c=a/b
return c

if __name__ == "__main__":
try:
# Read two values from the console
a = float(input("Enter the value of a (must be greater than 0): "))
b = float(input("Enter the value of b: "))

# Call the function DivExp and print the result


result = DivExp(a, b)
print(f"The result of the division is: {result}")

except AssertionError as e:
print(f"Error: {e}")

except ZeroDivisionError as e:
print(f"Error: {e}")
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.
def main():
# Read the number of complex numbers to be added (N >= 2)
N = int(input("Enter the number of complex numbers (N >= 2): "))
if N < 2:
print("N must be greater than or equal to 2.")
return

# Read N complex numbers from the console


complex_numbers = []
for i in range(N):
real = float(input(f"Enter the real part of complex number {i + 1}: "))
imag = float(input(f"Enter the imaginary part of complex number {i + 1}: "))
complex_numbers.append(Complex(real, imag))

# Compute the sum of the N complex numbers


sum_complex = complex_numbers[0]
for i in range(1, N):
sum_complex += complex_numbers[i]

# Print the result


print(f"The sum of the {N} complex numbers is: {sum_complex}")

if __name__ == "__main__":
main()} + {self.imag}i"
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.]
class Student:
def __init__(self, name, usn):
self.name = name
self.usn = usn
self.marks = [] # List to store marks in three subjects
self.total_marks = 0
self.percentage = 0.0

def getMarks(self):
print(f"Enter marks for {self.name} (USN: {self.usn}):")
for i in range(3):
mark = float(input(f"Subject {i+1} marks: "))
self.marks.append(mark)

# Calculate total marks


self.total_marks = sum(self.marks)

# Calculate percentage
self.percentage = self.total_marks / 3

def display(self):
print("\nScore Card")
print("----------")
print(f"Name: {self.name}")
print(f"USN: {self.usn}")
for i in range(3):
print(f"Subject {i+1} marks: {self.marks[i]}")
print(f"Total Marks: {self.total_marks}")
print(f"Percentage: {self.percentage:.2f}%")
# Main Program
if __name__ == "__main__":
# Read student details
name = input("Enter the student's name: ")
usn = input("Enter the student's USN: ")

# Create Student object


student = Student(name, usn)

# Get marks and display scorecard


student.getMarks()
student.display()

You might also like