# PYTHON LAB MANUAL : PART I

Dr. Thyagaraju G S and Palguni G T

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

Method1:

Output :

2.Develop a program to read the name and year of birth of a person. Display whether the person is a senior citizen or not.

Source Code:

Sample Output 1

Sample Output 2

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

Source Code

Output 1

Output 2

4.Write a function to calculate factorial of a number. Develop a program to compute binomial coefficient (Given N and R).

Source Code :

Output 1:

Output 2 :

5. Read N numbers from the console and create a list. Develop a program to print mean, variance and standard deviation with suitable messages.

Method1 : Without using Library functions

Source Code

Sample Output 1 :

Sample Output 2

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

Source Code :

Output :

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

Source Code :

``````from collections import OrderedDict
import numpy as np
import itertools
text = open("spamXY.txt")

def sort_dict_by_value(d, reverse = False):
return dict(sorted(d.items(), key = lambda x: x, reverse = reverse))

# Create an empty dictionary
d = dict()

# Loop through each line of the file
for line in text:
# Remove the leading spaces and newline character
line = line.strip()

# Convert the characters in line to
# lowercase to avoid case mismatch
line = line.lower()

# Split the line into words
words = line.split(" ")

# To eliminate  delimiters.
for word in words:
word = word.replace(".","")
word = word.replace(",","")
word = word.replace(":","")
word = word.replace(";","")
word = word.replace("!","")
word = word.replace("*","")

# Iterate over each word in line
for word in words:
# Check if the word is already in dictionary
if word in d:
# Increment count of word by 1
d[word] = d[word] + 1
else:
# Add the word to dictionary with count 1
d[word] = 1
print("\n Sorted dictionary elements by frequency [Descending order]:\n")
d1 =sort_dict_by_value(d, True)
print(d1)
print("\n")

N= int(input("Enter the number of top frequency words to be displayed: \n"))
print("\nThe {0} most frequently appearing words are : \n".format(N))
out = dict(itertools.islice(d1.items(),N))
for i in out:
print(i)``````

Input File :

Output :

```Sorted dictionary elements by frequency (Descending order):

{'quantum': 6, 'and': 5, 'a': 4, 'computer': 4, 'of': 3, 'the': 3, 'is': 2, 'physical': 2, 'could': 2, 'in': 2, 'that': 1, 'exploits': 1, 'mechanical': 1, 'phenomena.': 1, 'at': 1, 'small': 1, 'scales,': 1, 'matter': 1, 'exhibits': 1, 'properties': 1, 'both': 1, 'particles': 1, 'waves,': 1, 'computing': 1, 'leverages': 1, 'this': 1, 'behavior': 1, 'using': 1, 'specialized': 1, 'hardware.': 1, 'classical': 1, 'physics': 1, 'cannot': 1, 'explain': 1, 'operation': 1, 'these': 1, 'devices,': 1, 'scalable': 1, 'perform': 1, 'some': 1, 'calculations': 1, 'exponentially': 1, 'faster': 1, 'than': 1, 'any': 1, 'modern': 1, '"classical"': 1, 'computer.': 1, 'particular,': 1, 'large-scale': 1, 'break': 1, 'widely-used': 1, 'encryption': 1, 'schemes': 1, 'aid': 1, 'physicists': 1, 'performing': 1, 'simulations;': 1, 'however,': 1, 'current': 1, 'state': 1, 'art': 1, 'still': 1, 'largely': 1, 'experimental': 1, 'impractical.': 1}

Enter the number of top frequency words to be displayed:
10

The 10 most frequently appearing words are :

quantum
and
a
computer
of
the
is
physical
could
in```

8. 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()].

Input file :

Source code :

``````infile = open("spamXY.txt", "r")
words = []
for line in infile:
line = line.strip()
line = line.lower()
temp = line.split()
for word in temp:
word = word.replace(".","")
word = word.replace(",","")
word = word.replace(":","")
word = word.replace(";","")
word = word.replace("!","")
word = word.replace("*","")
word = word.replace("","")
for i in temp:
words.append(i)
infile.close()
words.sort()
print("Sorted words : ")
print(words)
# writing the sorted words into result.txt
outfile = open("result.txt", "w")
for i in words:
outfile.writelines(i)
outfile.writelines("\n")
outfile.close()``````

Output file :

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

Source Code :

``````import zipfile, os
folder = input("Enter the folder name in the current working directory : ")
folder = os.path.abspath(folder) # make sure folder is absolute
number = 1
while True:
zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
if not os.path.exists(zipFilename):
break
number = number + 1
# Create the zip file.
print('Creating %s...' % (zipFilename))
backupZip = zipfile.ZipFile(zipFilename, 'w')
# Walk the entire folder tree and compress the files in each folder.
for foldername, subfolders, filenames in os.walk(folder):
print('Adding files in %s...' % (foldername))
# Add the current folder to the ZIP file.
backupZip.write(foldername)
# Add all the files in this folder to the ZIP file.
for filename in filenames:
if filename.startswith(os.path.basename(folder) + '_') and filename.endswith('.zip'):
continue # don't backup the backup ZIP files
backupZip.write(os.path.join(foldername, filename))
backupZip.close()
print('Done.')``````

Output :

Compressed file in a given directory :

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

Source Code :

``````def DivExp(a,b):
assert a>0,"a must be > 0"
if b == 0:
raise ZeroDivisionError;
else: c = a/b
return c

a = int(input("Enter the value of a :"))
b = int(input("Enter the value of b :"))
r = DivExp(a,b)
print("The value of {0}/{1} = {2}".format(a,b,r))``````

Output1 :

Output2:

Output3 :

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

Source Code 1 using functions and class:

``````# Function to add two complex numbers
# creating temporary variable
temp=Complex(0, 0)
# adding real part of complex numbers
temp.real = C1.real + C2.real;
# adding Imaginary part of complex numbers
temp.imaginary = C1.imaginary + C2.imaginary;
# returning the sum
return temp;

# Class to represent a Complex Number
class Complex:
def __init__(self, tempReal, tempImaginary):
self.real = tempReal;
self.imaginary = tempImaginary;

# variable csum for Storing the sum of complex numbers
csum = Complex(0, 0) # inital value of csum set to 0,0
n = int(input("Enter the value of n : "))
for i in range(1,n+1):
realPart = int(input("Enter the Real Part of complex number {0}:".format(i)))
imgPart =int(input("Enter the Imaginary Part of complex number {0}:".format(i)))
c = Complex(realPart,imgPart)
# printing the sum
print("Sum of {0} complex numbers is :".format(n))
print(csum.real, "+i*"+ str(csum.imaginary))``````

Sample Output 1 :

Source Code 2 using Methods and class:

``````class Complex:
def __init__(self, tempReal, tempImaginary):
self.real = tempReal;
self.imaginary = tempImaginary;
# creating temporary variable
temp=Complex(0, 0)
# adding real part of complex numbers
temp.real = C1.real + C2.real;
# adding Imaginary part of complex numbers
temp.imaginary = C1.imaginary + C2.imaginary;
# returning the sum
return temp;
# for Storing the sum
csum = Complex(0, 0)
n = int(input("Enter the value of n : "))
for i in range(1,n+1):
realPart = int(input("Enter the Real Part of complex number {0}:".format(i)))
imgPart= int(input("Enter the Imaginary Part of complex number {0}:".format(i)))
c = Complex(realPart,imgPart)
# printing the sum
print("Sum of {0} complex numbers is :".format(n))
print(csum.real, "+i*"+ str(csum.imaginary))``````

Sample Output :

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

Source Code :

``````class Student:
marks = []
def getData(self, name, USN,max_marks, m1, m2, m3):
Student.name = name
Student.USN = USN
Student.max_marks = max_marks
Student.marks.append(m1)
Student.marks.append(m2)
Student.marks.append(m3)

def displayData(self):
print ("Name is: ", Student.name)
print ("USN is: ", Student.USN)
#print ("Marks in subject 1: ", Student.marks)
#print ("Marks in subject 2: ", Student.marks)
#print ("Marks in subject 3: ", Student.marks)
print ("Marks are: ", Student.marks)
print ("Total Marks is: ", self.total())
print ("Average Marks is: ", self.average())
print ("Percentage Marks is: ", self.percentage())

def total(self):
return (Student.marks + Student.marks +Student.marks)

def average(self):
return ((Student.marks + Student.marks +Student.marks)/3)

def percentage(self):
return ((self.average()/Student.max_marks)*100)

name = input("Enter the name: ")
usn = int (input("Enter the usn: "))
max_marks = int (input("Enter the max_marks (25/50/100/Any max):"))
m1 = int (input("Enter the marks in the first subject out of {0}:".format(max_marks)))
m2 = int (input("Enter the marks in the second subject out of {0}:".format(max_marks)))
m3 = int (input("Enter the marks in the third subject out of {0}:".format(max_marks)))

s1 = Student()
s1.getData(name, usn,max_marks,m1, m2, m3)
s1.displayData()``````

Sample Output :

``````Enter the name: Thyagu
Enter the usn: 12345
Enter the max_marks (25/50/100/Any max):25
Enter the marks in the first subject out of 25:23
Enter the marks in the second subject out of 25:21
Enter the marks in the third subject out of 25:21
Name is:  Thyagu
USN is:  12345
Marks are:  [23, 21, 21]
Total Marks is:  65
Average Marks is:  21.666666666666668
Percentage Marks is:  86.66666666666667``````