Python Lab Manual - 115758 - Removed
Python Lab Manual - 115758 - Removed
2
3
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.
4
2. a. Develop a program to generate Fibonacci sequence of length
(N). Read N from the console.
5
b. Write a function to calculate factorial of a number. Develop a
program to compute binomial coefficient (Given N and R).
6
3. Read N numbers from the console and create a list . Develop a
program to print mean , variance and standard devia on with
suitable messages.
OUTPUT:
Enter the number of elements in your list : 5
1: 234
2: 678
3: 209
4: 985
5: 756
The length of list1 is 5
List Contents [234, 678, 209, 985, 756]
Mean = 572.4
Variance = 92334.64
Standard Deviation = 303.87
7
04. Read a mul -digit number (as chars) from the console. Develop
a program to print the frequency of each digit with suitable
messages.
# method 1
num = input(“Input multi-digit number: “)
n = num._len_()
n0,n1,n2,n3,n4,n5,n6,n7,n8,n9 = 0,0,0,0,0,0,0,0,0,0
for i in range(n):
if num[i] == ‘0’:
n0+=1
if num[i] == ‘1’:
n1+=1
if num[i] == ‘2’:
n2+=1
if num[i] == ‘3’:
n3+=1
if num[i] == ‘4’:
n4+=1
if num[i] == ‘5’:
n5+=1
if num[i] == ‘6’:
n6+=1
if num[i] == ‘7’:
n7+=1
if num[i] == ‘8’:
n8+=1
if num[i] == ‘9’:
n9+=1
dfreq = [n0,n1,n2,n3,n4,n5,n6,n7,n8,n9]
print(“The number “, num, “has: “)
for i in range(10):
if dfreq[i] == 0:
continue
print(i , “digit”, dfreq[i], “times. “)
OUTPUT:
Enter a number : 98769899
The number entered is : 98769899
7 occurs 1 times
9 occurs 4 times
8 occurs 2 times
6 occurs 1 times
8
# method 2
uniqDig = set(num)
#print(uniqDig)
OUTPUT:
Enter a number : 98769899
The number entered is : 98769899
7 occurs 1 times
9 occurs 4 times
8 occurs 2 times
6 occurs 1 times
9
05. Develop a program to print 10 most frequently appearing words
in a text file. [Hint: Use dic onary with dis nct words and their
frequency of occurrences. Sort the dic onary in the reverse order of
frequency and display dic onary slice of first 10 items.]
Ifile = open(“kseem.txt”)
dict_words = {}
for line in ifile :
words = line.split()
for word in words :
dict_words[word] = dict_words.get(word,0) + 1
list_words = []
for key, val in dict_words.items() :
list_words.append((val,key))
list_words.sort(reverse = True)
print(“ The slice of first 10 items of sorted dictionary are : “)
print(list_words[0:10])
OUTPUT:
The slice of first 10 items of sorted dictionary are:
[ (4,’a’) , (2, ‘to’), (2, ‘the’), (2, ‘program’), (2,’print’), (2 , ‘Develop’), (1, ‘words’), (1,
‘with’), (1, ‘text’), (1, ‘suitable’) ]
10
06. 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(). ]
OUTPUT:
[‘.’, ‘10’,’Develop’,’Develop’, ‘a’,’a’,’a’,’appearing’, ‘console’, ‘digit’,
éach’,’file’,from’,’frequency’,’frequently’, ‘number’,’words’,text’]
11
07. Develop a program to backing Up a given Folder (Folder in a
working directory) into a ZIP File by using relevant modules and
suitable methods.
import zipfile , os
def backupToZip (folder):
folder = os.pth.abspath(folder)
zipFilename = “ “
number = 1
while True :
zipFilenme = os.path.basename(folder) + ‘_’ + str(number) + ‘.zip’
if not os.path.exists(zipFilename):
break
number = number + 1
print(‘ Creating %s………’%(zipFilename))
backupZip = zipfile.zipFile(zipFilename, ‘w’)
for foldername ,subfolders, filenames in os.walk(folder):
print(‘Adding files in %s ‘ %(foldername))
backupZip.write(foldername)
for filename in filenames:
if filename.startswith(os.path.basename(folder) +’_’) and
filename.endswith(‘zip’):
backupzip.write(os.path.join(foldername,filename))
backupZip.close()
print(‘Done’)
backupTozip(‘C:\\Users\\CSELAB\\Desktop\\a@numbers’)
OUTPUT:
Creating a@numbers_.zip...
Adding files in C:\\Users\\CSELAB\\Desktop\\a@numbers…
Adding files in C:\\Users\\CSELAB\\Desktop\\a@numbers1…
Adding files in C:\\Users\\CSELAB\\Desktop\\a@numbers2…
Adding files in C:\\Users\\CSELAB\\Desktop\\a@numbers3…
Adding files in C:\\Users\\CSELAB\\Desktop\\a@numbers4…
Done
12
08. Write a func on named DivExp which takes two parameters a, b
and returns a value c (c=a/b). Write suitable asser on for a>0 in
func on DivExp and raise an excep on for when b=0 . Develop a
suitable program which reads two values from the console and calls
a func on DivExp.
def DivExp(a,b):
try:
assert a>0, “Number a is Negative.”
if b == 0:
raise ZeroDivisionError(“Zero Division Error”)
c=a/b
return c
except ZeroDivisionError as x:
print(x)
except AssertionError as x:
print(‘Assertion failure: “+ str(x))
x,y = map(int, input(“Enter two integers”).strip.split())
print(x,y)
print(DivExp(x,y))
OUTPUT:
Enter two integers : -23 8
-23 8
Assertion failure: Number a is Negative
None
13
09. Define a func on which takes two objects represen ng complex
numbers and returns new complex number with a addi on 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 addi on of N complex numbers.
class Complex :
def __init__(self, real =0 , img=0):
self.real = real
self.img = img
def _add__(c1,c2):
return Complex(c1.real + c2.real , c1.img + c2.real)
def __str__(self):
return (“{} +j ({})”, format (self.real , self.img)
ca = Complex(-2,-5)
cb = Complex(12,8)
print( ca , “+” , cb , “=”, ( ca+cb ) )
Complex_list = [ ]
n = int(input(“How many complex numbers do you want to add “))
for i in range (n):
m, n = map(float, input (“Enter the real and img cords of complex number with
two numbers separated with space “)
Complex_list.append ( Complex(m,n) )
sum_series = Complex()
for x in Complex_list :
sum_series += x
print(“The sum of given complex numbers is “, sum_series)
OUTPUT :
-2 + j(-5) + 12 + j(8) = 10 + j(3)
<class ‘__main__.Complex’> 2263445475784
How many Complex numbers do you want to add? 2
Enter the real and img cords of complex number with two numbers separated with
space : 1 2
Enter the real and img cords of complex number with two numbers separated with
space : 3 4
The sum of given complex number is 10 + j(3)
14
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 ini alize 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= ’ ’,marks= [ ]):
self.name = name
self.usn = usn
self.marks = list ()
def getMarks (self):
x = map (int, input(“Enter marks scored in 3 subjects with each number
separated by space : “)
self.marks += x
def getDetails (self):
self.name = input(“Enter name : “)
self.usn = input(“Enter usn : “)
def display (self):
print(“Name : “, self.name )
print(“USN :”, self.usn )
print(“Marks : “, self.marks)
total = 0
for x in self.marks :
total += x
print(“Total Marks : “, total , “\t Percentage”, total/3, ”%”)
x = Student()
x.getDetails()
x.getMarks()
x.display()
OUTPUT:
15
16