Updated Python Manual2024-25
Updated Python Manual2024-25
1.a Develop a python code to read student details like name, usn, marks in three subjects and Display
the results like total_marks and percentage, with suitable messages
CODE:
name= input("Student please enter your name : ")
totalmarks=s1+s2+s3
percentage=totalmarks/3
................................................................................................................................................................
Program Output
CODE:
personName = input("Enter the person name: ")
personYOB=int(input("Enter your birth year:"))
currentYear = int(input("Enter the Current Year: "))
if currentYear-personYOB >= 60:
print(personName,"is a senior person...")
else:
print(personName,"is not a senior person...")
................................................................................................................................................................
Program output1
................................................................................................................................................................
Program output2
CODE:
0
1
1
2
3
5
8
13
2.b Write a function to calculate factorial of a number.
CODE:
num=int(input("Enter a number:"))
factorial = 1
if num<0:
print("Factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial=factorial*i
print("The factorial of",num,"is",factorial)
OUTPUT 1:
Enter a number: 4
The factorial of 4 is 24
OUTPUT 2:
Enter a number: 0
The factorial of 0 is 1
OUTPUT 3:
Enter a number: -4
Factorial does not exist for negative numbers
2.c Python program to compute binomial coefficient (Given N and R).
CODE:
import math
def binomial_coefficient( n, r ):
if r > n:
return 0
else:
result = binomial_coefficient(n, r)
................................................................................................................................................................
Program output
................................................................................................................................................................
CODE:
import numpy as np
#creating an empty list
list = [ ]
#number of elements as input
n=int(input("Enter number of elements:"))
print(list)
#Calculating mean using mean()
print(np.mean(list))
#Calculating variance using var()
print(np.var(list))
#Calculating standard deviation using std()
print(np.std(list))
OUTPUT:
Enternumberofelements:8
2
4
4
4
5
5
7
9
[2,4,4,4,5,5,7,9]
5.0
4.0
2.0
4. Read a multi-digit number (as chars) from the console. Develop a program to print the frequency of
each digit with suitable message.
CODE:
def count_digits():
if not num.isdigit():
else:
unique_digits = []
unique_digits.append(digit)
count_digits()
................................................................................................................................................................
program output
Enter a number: 35354353555
Digit 3: 4 time(s)
Digit 5: 6 time(s)
Digit 4: 1 time(s)
................................................................................................................................................................
Enter a number: 6786869980808088084
Digit 6: 3 time(s)
Digit 7: 1 time(s)
Digit 8: 8 time(s)
Digit 9: 2 time(s)
Digit 0: 4 time(s)
Digit 4: 1 time(s)
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]
CODE:
import re
words = []
for line in f:
words.extend(line.split())
count = Counter(words)
top10 = count.most_common(10)
print(top10)
................................................................................................................................................................
Note :Create a text file with name text.txt and write this content into that file
Output
[('are', 5), ('hello', 5), ('Hello', 4), ('you', 4), ('is', 3), ('test', 3), ('again', 3), ('how', 3), ('world', 2),
('hi',2)]
................................................................................................................................................................
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()].
CODE:
bands = []
filename = 'bands.txt'
with open(filename) as fin:
for line in fin:
bands.append(line.strip())
bands.sort(key=int)
print(bands)
filename = 'sorted.txt'
with open(filename, 'w') as fout:
for band in bands:
fout.write(band + '\n')
................................................................................................................................................................
Note : This program requires two text files ,these files must be created before execution of this
python program.First text file , it is an input file for python program , and copy and paste below content
into band.txt file.
band.txt
11
11
# 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
Code:
import os
from zipfile import ZipFile
import shutil
def backup_folder(folder_name):
# Check if folder exists
if os.path.exists(folder_name):
# Create a ZIP file with the same name as the folder
zip_file_name = folder_name + '.zip'
# Use shutil.make_archive to create a ZIP archive
shutil.make_archive(folder_name, 'zip', folder_name)
print(f'Folder {folder_name} backed up to {zip_file_name}')
else:
print(f'Folder {folder_name} does not exist')
# Example usage
folder_name = 'abcd'
backup_folder(folder_name)
.....................................................................................................................................................
Output:
Note :
This progrm requires one input as a folder , here i have created folder with name ‘abcd’
After execution of this program , you will get output as zip folder with name ‘abcd.zip
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.
CODE:
if b == 0:
return None
return a / b
print("Result:", result)
................................................................................................................................................................
Output
Enter first number: 10
Enter second number: 5
Result: 2.0
................................................................................................................................................................
Output
Enter first number: -10
Enter second number: 5
AssertionError: Dividend must be positive.
................................................................................................................................................................
Output
Enter first number: 10
Enter second number: 0
Divide by zero error.
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.
CODE:
class Complex ():
def initComplex(self):
self.realPart = int(input("Enter the Real Part: "))
self.imgPart = int(input("Enter the Imaginary Part: "))
def display(self):
print(self.realPart,"+",self.imgPart,"i", sep="")
def sum(self, c1, c2):
self.realPart = c1.realPart + c2.realPart
self.imgPart = c1.imgPart + c2.imgPart
c1 = Complex()
c2 = Complex()
c3 = Complex()
print("Enter first complex number")
c1.initComplex()
print("First Complex Number: ", end="")
c1.display()
print("Enter second complex number")
c2.initComplex()
print("Second Complex Number: ", end="")
c2.display()
print("Sum of two complex numbers is ", end="")
c3.sum(c1,c2)
c3.display()
................................................................................................................................................................
OUTPUT:
Enter first complex number
Enter the Real Part: 4
Enter the Imaginary Part: 6
First Complex Number: 4+6i
Enter second complex number
Enter the Real Part: 4
Enter the Imaginary Part: 6
Second Complex Number: 4+6i
Sum of two complex numbers is 8+12i
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.
CODE:
class Student:
def __init__(self, name, usn):
self.name = name
self.usn = usn
self.marks = []
self.total = 0
def getMarks(self):
for i in range(3):
marks = int(input("Enter marks in subject " + str(i+1) + ": "))
self.marks.append(marks)
self.total += marks
def display(self):
print("Name:", self.name)
print("USN:", self.usn)
print("Marks:", self.marks)
print("Total:", self.total)
print("Percentage:", self.total / 3 * 100)
OUTPUT:
Enter name: mki
Enter USN: 2sa1234
Enter marks in subject 1: 88
Enter marks in subject 2: 98
Enter marks in subject 3: 99
Name: mki
USN: 2sa1234
Marks: [88, 98, 99]
Total: 285
Percentage: 9500.0