Introduction to Python Programming(BPLCK105B)
1.aDevelop a program to read the student details like Name, USN, and Marks in three subjects. Dis-
play the student details, total marks and percentage with suitable messages.
stName = input("Enter the name of the student : ")
stUSN = input("Enter the USN of the student : ")
stMarks1 = int(input("Enter marks in Subject 1 : "))
stMarks2 = int(input("Enter marks in Subject 2 : "))
stMarks3 = int(input("Enter marks in Subject 3 : "))
total=stMarks1+stMarks2+stMarks3
percentage=total/3
print("Student Details\n")
print("Name :", stName)
print("USN :", stUSN)
print("Marks 1 :", stMarks1)
print("Marks 2 :", stMarks2)
print("Marks 3 :", stMarks3)
print("Total :",total )
print("Percent :",percentage)
if percentage>=90:
print("Distinction")
elif percentage>=75 and percentage<90:
print("first class ")
elif percentage>=60 and percentage<75:
print("second class")
elif percentage >=35 and percentage<60:
print("just pass")
else:
print("fail")
Swetha B R , Dept. of CSE, RIT ,Hassan Page 1
Introduction to Python Programming(BPLCK105B)
OUTPUT
Enter the name of the student : Jenny
Enter the USN of the student : 4RA21EC001
Enter marks in Subject 1 : 85
Enter marks in Subject 2 : 92
Enter marks in Subject 3 : 89
Student Details
Name : Jenny
USN : 4RA21EC001
Marks 1 : 85
Marks 2 : 92
Marks 3 : 89
Total : 266
Percent : 88.66666666666667
first class
Swetha B R , Dept. of CSE, RIT ,Hassan Page 2
Introduction to Python Programming(BPLCK105B)
1.b .Develop a program to read the name and year of birth of a person. Display whether
the personis a senior citizen or not.
from datetime import date
perName = input("Enter the name of the person : ")
perDOB = int(input("Enter his year of birth : "))
curYear = date.today().year
perAge = curYear - perDOB
if (perAge > 60):
print(perName, "aged", perAge, "years is a Senior Citizen.")
else:
print(perName, "aged", perAge, "years is not a Senior Citizen.")
OUTPUT
Enter the name of the person : Bob
Enter his year of birth : 1972
Bob aged 51 years is not a Senior Citizen.
Swetha B R , Dept. of CSE, RIT ,Hassan Page 3
Introduction to Python Programming(BPLCK105B)
2.a. Develop a program to generate Fibonacci sequence of length (N). Read N from the
console.
num = int(input("Enter the Fibonacci sequence length to be generated : "))
firstTerm = 0
secondTerm = 1
print("The Fibonacci series with", num, "terms is :")
print(firstTerm)
print(secondTerm)
for i in range(2,num):
curTerm = firstTerm + secondTerm
print(curTerm)
firstTerm = secondTerm
secondTerm = curTerm
OUTPUT
Enter the Fibonacci sequence length to be generated : 10
The Fibonacci series with 10 terms is :
0
1
1
2
3
5
8
13
21
34
Swetha B R , Dept. of CSE, RIT ,Hassan Page 4
Introduction to Python Programming(BPLCK105B)
2.b. Write a function to calculate factorial of a number. Develop a program to compute binomial
coefficient (Given N and R).
def fact(num):
if num == 0:
return 1
else:
return num * fact(num-1)
n = int(input("Enter the value of N : "))
r = int(input("Enter the value of R (R cannot be negative or greater than N): "))
nCr = fact(n)/(fact(r)*fact(n-r))
print(n,'C',r,'=',nCr)
OUTPUT
Enter the value of N : 5
Enter the value of R (R cannot be negative or greater than N): 2
5 C 2 = 10.0
Swetha B R , Dept. of CSE, RIT ,Hassan Page 5
Introduction to Python Programming(BPLCK105B)
3. Read N numbers from the console and create a list. Develop a program to print mean,
variance and standard deviation with suitable messages.
from math import sqrt
myList = [ ]
num = int(input("Enter the number of elements in your list : "))
for i in range(num):
val = int(input("Enter the element : "))
myList.append(val)
print("The length of list1 is",len(myList))
length=len(myList)
print("List Contents", myList)
total = 0
for elem in myList:
total += elem #total=total+elem
mean = total / num
total = 0
for elem in myList:
total += (elem - mean) * (elem - mean) # square(elem-mean)
variance = total / num
stdDev = sqrt(variance)
print("Mean =", mean)
print("Variance =", variance)
print("Standard Deviation =", stdDev)
Swetha B R , Dept. of CSE, RIT ,Hassan Page 6
Introduction to Python Programming(BPLCK105B)
OUTPUT
Enter the number of elements in your list : 10
Enter the element : 1
Enter the element : 2
Enter the element : 3
Enter the element : 4
Enter the element : 5
Enter the element : 6
Enter the element : 7
Enter the element : 8
Enter the element : 9
Enter the element : 10
The length of list1 is 10
List Contents [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Mean = 5.5
Variance = 8.25
Standard Deviation = 2.8722813232690143
Swetha B R , Dept. of CSE, RIT ,Hassan Page 7
Introduction to Python Programming(BPLCK105B)
4. Read a multi-digit number (as chars) from the console. Develop a program to print the frequency of
each digit with suitable message.
num = input("Enter a number : ")
print("The number entered is :", num)
uniqDig = set(num)
print(uniqDig)
for elem in uniqDig:
print(elem, "occurs", num.count(elem), "times")
OUTPUT
Enter a number : 123548113247851684621
The number entered is : 123548113247851684621
{'2', '6', '5', '1', '4', '3', '7', '8'}
2 occurs 3 times
6 occurs 2 times
5 occurs 2 times
1 occurs 5 times
4 occurs 3 times
3 occurs 2 times
7 occurs 1 times
8 occurs 3 times
Swetha B R , Dept. of CSE, RIT ,Hassan Page 8
Introduction to Python Programming(BPLCK105B)
5. Develop a program to print 10 most frequently appearing words in a text file. [Hint: Use
dictio- nary 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]
file=open("text.txt",'r')
freq_dict={}
for line in file.readlines():
for word in line.split():
if word not in freq_dict:
freq_dict[word]=1
else:
freq_dict[word]+=1
file.close()
freq_words=sorted(freq_dict.items(),key=lambda x:x[1], reverse=True)[:10]
print("Top 10 most occuring words in given file are\n")
for x in freq_words:
print("word: "+x[0]+ " with occurance" +str(x[1]))
Swetha B R , Dept. of CSE, RIT ,Hassan Page 9
Introduction to Python Programming(BPLCK105B)
OUTPUT
word: is with occurance39
word: the with occurance36
word: and with occurance35
word: to with occurance32
word: in with occurance29
word: of with occurance24
word: 5G with occurance18
word: it with occurance14
word: for with occurance13
word: antenna with occurance13
Swetha B R, Dept of CSE , RIT, Hassan Page 10
Introduction to Python Programming(BPLCK105B)
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()].
readfile=open("text.txt",'r')
words=[]
for line in readfile.readlines():
temp=line.split()
for word in temp:
word=word.strip()
words.append(word)
readfile.close()
print("length of list is",len(words))
words.sort()
print("file after sorting")
print(words)
sortedfile=open("sortedfile.txt","w")
for word in words:
sortedfile.writelines(word)
sortedfile.writelines("\n")
sortedfile.close()
OUTPUT
length of list is 31
file after sorting
['agriculture', 'and', 'and', 'and', 'banking', 'because', 'communication', 'communication', 'every', 'fastest',
'from', 'gained.', 'growing', 'grown', 'has', 'has', 'healthcare', 'in', 'is', 'is', 'it', 'it', 'sector', 'technology', 'the', 'to',
'transportation.', 'used', 'wider', 'wireless', 'wireless']
Text File(Sorted File)
agriculture
and
and
and
Swetha B R , Dept of CSE, RIT ,Hassan Page 11
Introduction to Python Programming(BPLCK105B)
banking
because
communication
communication
every
fastest
from
gained.
growing
grown
has
has
healthcare
in
is
is
it
it
sector
technology
the
to
transportation.
used
wider
wireless
wireless
Swetha B R , Dept of CSE, RIT ,Hassan Page 12
Introduction to Python Programming(BPLCK105B)
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 zipfile, os
def backupToZip(folder):
folder = os.path.abspath(folder)
number = 1
while True:
zipFilename = 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:
newBase = os.path.basename(folder)
if filename.startswith(newBase) and filename.endswith('.zip'):
continue
backupZip.write(os.path.join(foldername, filename))
backupZip.close()
print('Done.')
# Main Program
backupToZip(r'C:\Users\HP\Desktop\Ranjini')
OUTPUT
Done
Swetha B R , Dept of CSE, RIT ,Hassan Page 13
Introduction to Python Programming(BPLCK105B)
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):
try:
c=a/b
print(c)
except ZeroDivisionError:
print("Error:Denominator cannot be zero/canot diveide by zero")
num1=int(input("Enter first number"))
num2=int(input("Enter second number"))
DivExp(num1,num2)
OUTPUT
Case1:
Enter first number10
Enter second number2
5.0
Case2:
Enter first number10
Enter second number0
Error:Denominator cannot be zero/canot diveide by zero
Swetha B R , Dept of CSE, RIT ,Hassan Page 14
Introduction to Python Programming(BPLCK105B)
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 initComplex(self):
self.realPart = int(input("Enter the Real Part: "))
self.imgPart = int(input("Enter the Imaginary Part: "))
def display(self):
#print(str(self.realPart)+"+"+ str(self.imgPart)+"i")
print(self.realPart,"+",self.imgPart,"i")
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: ")
c1.display()
print("Enter second complex number")
c2.initComplex()
print("Second Complex Number: ")
c2.display()
print("Sum of two complex numbers is ")
c3.sum(c1,c2)
c3.display()
Swetha B R , Dept of CSE, RIT ,Hassan Page 15
Introduction to Python Programming(BPLCK105B)
OUTPUT
Enter first complex number
Enter the Real Part: 2
Enter the Imaginary Part: 5
First Complex Number:
2+5i
Enter second complex number
Enter the Real Part: 5
Enter the Imaginary Part: 8
Second Complex Number:
5+8i
Sum of two complex numbers is
7 + 13 i
Swetha B R , Dept of CSE, RIT ,Hassan Page 16
Introduction to Python Programming(BPLCK105B)
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 Studentdetail:
def use_init(self):
name = input("Enter name: ")
usn = input("Enter USN: ")
self.name = name
self.usn = usn
self.marks = []
self.total = 0
def getMarks(self):
m1=int(input("enter sub1marks") )
m2=int(input("enter sub2marks") )
m3=int(input("enter sub3marks"))
self.marks.append(m1)
self.marks.append(m2)
self.marks.append(m3)
self.total=int(m1+m2+m3)
def display(self):
print("Name:", self.name)
print("USN:", self.usn)
print("Marks:", self.marks)
print("Total:", self.total)
print("Percentage:", self.total/3)
# Main program
student = Studentdetail()
student.use_init()
student.getMarks()
student.display()
Swetha B R , Dept of CSE, RIT ,Hassan Page 17
Introduction to Python Programming(BPLCK105B)
OUTPUT
Enter name: 'Ananya'
Enter USN: '4RA21EC001'
enter sub1marks85
enter sub2marks95
enter sub3marks87
Name: 'Ananya'
USN: '4RA21EC001'
Marks: [85, 95, 87]
Total: 267
Percentage: 89.0
Swetha B R , Dept of CSE, RIT ,Hassan Page 18