Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
18 views

Python Lab Programs

Uploaded by

kotarivardhan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Python Lab Programs

Uploaded by

kotarivardhan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

lOMoARcPSD|36118095

Python lab programs

Introduction to python programming (Visvesvaraya Technological University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Sanvi Shetty (saff2066@gmail.com)
lOMoARcPSD|36118095

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.

name = input('Enter the Name of Student ')

usn = input('Enter the USN of Student ')

marks1 = int(input('Enter the mark in first subject '))

marks2 = int(input('Enter the mark in second subject '))

marks3 = int(input('Enter the mark in third subject '))

total_marks = marks1 + marks2 + marks3

percentage = total_marks/300*100

print('Student Details are')

print('Name is ', name)

print('USN is ', usn)

print('Marks in first subject is ', marks1)

print('Marks in second subject is ', marks2)

print('Marks in third subject is ', marks3)

print('Total marks obtained is ', total_marks)

print('Percentage of Marks', percentage)

Downloaded by Sanvi Shetty (saff2066@gmail.com)


lOMoARcPSD|36118095

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 the Name')

year_of_birth = int(input('Enter birth year'))

current_year = int(input('Enter the present year'))

age = current_year - year_of_birth

if age>60 :

print('Senior Citizen')

else:

print('Not Senior Citizen')

Downloaded by Sanvi Shetty (saff2066@gmail.com)


lOMoARcPSD|36118095

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

def fibonacci_sequence(length):

sequence = [0, 1] # Initialize the sequence with the first two Fibonacci numbers

while len(sequence) < length:

next_number = sequence[-1] + sequence[-2] # Calculate the next Fibonacci number

sequence.append(next_number)

return sequence

# Read the length of the Fibonacci sequence from the console

n = int(input("Enter the length of the Fibonacci sequence: "))

# Generate the Fibonacci sequence

fibonacci = fibonacci_sequence(n)

# Print the sequence

print("Fibonacci sequence of length", n, ":", fibonacci)

Downloaded by Sanvi Shetty (saff2066@gmail.com)


lOMoARcPSD|36118095

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:

return 1

else:

return n * factorial(n - 1)

def binomial_coefficient(n, r):

coefficient = factorial(n) // (factorial(r) * factorial(n - r))

return coefficient

# Read the values of 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

coefficient = binomial_coefficient(n, r)

# Print the result

print("Binomial coefficient C(", n, ",", r, ") =", coefficient)

Downloaded by Sanvi Shetty (saff2066@gmail.com)


lOMoARcPSD|36118095

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 math

def calculate_mean(numbers):

return sum(numbers) / len(numbers)

def calculate_variance(numbers, mean):

squared_diff = [(x - mean) ** 2 for x in numbers]

return sum(squared_diff) / len(numbers)

def calculate_standard_deviation(variance):

return math.sqrt(variance)

# Read N numbers from the console

N = int(input("Enter the number of elements: "))

numbers = []

for i in range(N):

num = float(input(f"Enter number {i+1}: "))

numbers.append(num)

# Calculate mean, variance, and standard deviation

mean = calculate_mean(numbers)

variance = calculate_variance(numbers, mean)

standard_deviation = calculate_standard_deviation(variance)

# Print the results

print("Mean:", mean)

print("Variance:", variance)

print("Standard Deviation:", standard_deviation)

Downloaded by Sanvi Shetty (saff2066@gmail.com)


lOMoARcPSD|36118095

def count_digit_frequency(number):

frequency = [0] * 10 # Initialize a list to store the frequency of each digit

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

# Iterate through each character in the number

for digit in number:

if digit.isdigit():

# If the character is a digit, increment its frequency by 1

frequency[int(digit)] += 1

# Print the frequency of each digit

for i in range(10):

print("Frequency of digit {}: {}".format(i, frequency[i]))

# Read the multi-digit number from the console

number = input("Enter a multi-digit number: ")

# Call the function to count the frequency of each digit

count_digit_frequency(number)

Downloaded by Sanvi Shetty (saff2066@gmail.com)


lOMoARcPSD|36118095

5. Develop a program to print 10 most frequently appearing words in a text file.

def count_word_frequency(filename):
word_frequency = {}

# Read the text file


with open(filename, 'r') as file:
# Process each line
for line in file:
# Split the line into words
words = line.strip().split()

# Count the frequency of each word


for word in words:
# Increment the count for existing words
if word in word_frequency:
word_frequency[word] += 1
# Add new words to the dictionary
else:
word_frequency[word] = 1
return word_frequency

def print_top_10_words(word_frequency):
# Sort the dictionary in reverse order of frequency
sorted_words = sorted(word_frequency.items(), key=lambda x: x[1], reverse=True)

# Print the top 10 words


for word, frequency in sorted_words[:10]:
print(f"{word}: {frequency} occurrences")

# Provide the path to your text file


filename = "D:/ Documents/Python/test.txt"
word_frequency = count_word_frequency(filename)
print_top_10_words(word_frequency)

Downloaded by Sanvi Shetty (saff2066@gmail.com)


lOMoARcPSD|36118095

6. Develop a program to sort the contents of a text file and write the sorted contents into a
separate text file

def sort_file_contents(input_filename, output_filename):

# Read the input file

with open(input_filename, 'r') as input_file:

lines = input_file.readlines()

# Remove leading and trailing whitespace from each line

lines = [line.strip() for line in lines]

# Sort the lines in ascending order

lines.sort()

# Write the sorted contents to the output file

with open(output_filename, 'w') as output_file:

for line in lines:

output_file.write(line + '\n')

# Specify the input and output file names

input_filename = "D:/Documents/Python/test.txt"

output_filename = "D:/Documents/Python/Output.txt"

# Sort the contents of the input file and write to the output file

sort_file_contents(input_filename, output_filename)

Downloaded by Sanvi Shetty (saff2066@gmail.com)


lOMoARcPSD|36118095

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 zipfile

def backup_folder_to_zip(folder_name, zip_name):

# Get the absolute path of the folder and the zip file

folder_path = os.path.abspath(folder_name)

zip_path = os.path.abspath(zip_name)

# Check if the folder exists

if not os.path.exists(folder_path):

print(f"Error: Folder '{folder_path}' does not exist.")

return

try:

# Open the zip file in write mode

with zipfile.ZipFile(zip_path, 'w') as backup_zip:

# Walk through the folder and its subdirectories

for folder_root, sub_folder, files in os.walk(folder_path):

for file in files:

file_path = os.path.join(folder_root, file

# Calculate the relative path for the file inside the ZIP

relative_path = os.path.relpath(file_path, folder_path)

# Write the file to the ZIP

backup_zip.write(file_path, arcname=relative_path)

Downloaded by Sanvi Shetty (saff2066@gmail.com)


lOMoARcPSD|36118095

print(f"Backup of '{folder_path}' created at '{zip_path}'.")

except Exception as e:

print(f"An error occurred: {e}")

folder_to_backup = "F:/Python" # Change this to the folder you want to backup

backup_zip_name = "backup.zip" # Change this to the desired name for the backup ZIP file

backup_folder_to_zip(folder_to_backup, backup_zip_name)

Downloaded by Sanvi Shetty (saff2066@gmail.com)


lOMoARcPSD|36118095

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 a > 0, "Assertion Error: a should be greater than 0"

if b == 0:

raise ValueError("Error: Division by zero is not allowed")

return a / b

try:

a = float(input("Enter the value of a: "))

b = float(input("Enter the value of b: "))

result = DivExp(a, b)

print("Result:", result)

except (ValueError, AssertionError) as e:

print("Error:", e)

Downloaded by Sanvi Shetty (saff2066@gmail.com)


lOMoARcPSD|36118095

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.

class Complex:

def __init__(self, real, imaginary):

self.real = real

self.imaginary = imaginary

def __str__(self):

return f"{self.real} + {self.imaginary}i"

def add_complex_numbers(complex1, complex2):

new_real = complex1.real + complex2.real

new_imaginary = complex1.imaginary + complex2.imaginary

return Complex(new_real, new_imaginary)

# Main program

n = int(input("Enter the number of complex numbers (N >= 2): "))

if n < 2:

print("Please enter a value of N greater than or equal to 2.")

else:

total = Complex(0, 0)

for i in range(n):

print(f"Enter complex number {i + 1}:")

real = float(input("Real part: "))

imaginary = float(input("Imaginary part: "))

total = add_complex_numbers(total, Complex(real, imaginary))

print("\nSum of complex numbers:", total)

Downloaded by Sanvi Shetty (saff2066@gmail.com)


lOMoARcPSD|36118095

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

class Student:

def __init__(self, name, usn):

self.name = name

self.usn = usn

self.marks = [0, 0, 0]

self.total_marks = 0

self.percentage = 0.0

def getMarks(self):

for i in range(3):

self.marks[i] = float(input(f"Enter marks for subject {i + 1}: "))

self.total_marks += self.marks[i]

self.percentage = (self.total_marks / 300) * 100

def display(self):

print("\nScore Card")

print("Name:", self.name)

print("USN:", self.usn)

print("Marks in Subject 1:", self.marks[0])

print("Marks in Subject 2:", self.marks[1])

print("Marks in Subject 3:", self.marks[2])

print("Total Marks:", self.total_marks)

print("Percentage:", self.percentage, "%")

Downloaded by Sanvi Shetty (saff2066@gmail.com)


lOMoARcPSD|36118095

# Main program

name = input("Enter student's name: ")

usn = input("Enter student's USN: ")

student = Student(name, usn)

student.getMarks()

student.display()

Downloaded by Sanvi Shetty (saff2066@gmail.com)

You might also like