IV Semester BCA
Python Lab Programs
1. Write a program to demonstrate math function.
import math
n=eval(input("Enter the number : "))
print("Float Absolute value of ",n," is : ",math.fabs(n))
print("Ceil value of ",n," is : ",math.ceil(n))
print("Floor value of ",n," is : ",math.floor(n))
print("Exponential value of ",n," is : ",math.exp(n))
print("Log value of ",n," is : ",math.log(n))
print("Log value (Base10) of ",n," is : ",math.log10(n))
print("Sine value of ",n," is : ",math.sin(n))
print("Cosine value of ",n," is : ",math.cos(n))
print("Tangent value of ",n," is : ",math.tan(n))
print("Degrees value of ",n," is : ",math.degrees(n))
print("Radians value of ",n," is : ",math.radians(n))
print("Square root value of ",n," is : ",math.sqrt(n))
2. Program to calculate Body mass Index by accepting height and weight.
#Body Mass Index Calculation
w=eval(input("Enter weight (in kgs) : "))
h=eval(input("Enter height (in inches) : "))
m=0.025*h
bmi=w/(m*m)
print("BodyMassIndex for given inputs : ",bmi)
if bmi>0 and bmi<18:
print("BMI stage : Low Weight")
elif bmi>=18 and bmi<25:
print("BMI stage : Perfect")
else:
print("BMI stage : Over Weight")
3. Program to calculate percentage of marks and award grade.
maxmarks=int(input("Enter maximum marks"))
marksobt=int(input("Enter total mraks obtained"))
per=marksobt*(100/maxmarks)
if(per>=90.01 and per<=100):
grade="O outstanding"
elif(per>=80.01 and per<=90):
grade="A++ First class"
elif(per>=70.01 and per<=80):
grade="A+ First class"
elif(per>=60.01 and per<=70):
grade="A First class"
Dept of C.Sc NCB Python Lab Programs Page 1
elif(per>=55.01 and per<=60):
grade="B+ High second class"
elif(per>=50.01 and per<=55):
grade="B Second class"
elif(per>=40.01 and per<=50):
grade="c Pass class"
elif(per>=0 and per<=40):
grade="F Fail"
else:
print("Invalid percentage")
print("Percentage:",round(per,2))
print("Grade:",grade)
4. Program to generate prime numbers and calculate CPU time using time module.
from time import clock
m=eval(input("Enter max range "))
c=0
st=clock()
for i in range (2,m+1):
f=0
for j in range(2,i):
if i%j == 0:
f=1
break
if f==0:
print(i,end=' ')
c+=1
print()
el=clock() - st
print("No. of Prime no.s : ",c)
print("Time elapsed : ",el, " seconds")
5. Program to generate Fibonacci numbers using recursive function.
def fibo(n):
if n==0 or n==1:
return n
else:
return fibo(n-1)+fibo(n-2)
n=int(input("Enter value for n:"))
print("First",n,"Fibonacci numbers are:")
for i in range(n):
print(fibo(i),end=" ")
Dept of C.Sc NCB Python Lab Programs Page 2
6. Program to validate phone number using function decorator.
def decor(fun):
def check():
x=fun()
if(x.isdigit()!=True):
print("Invalid phone number, re enter phone number")
return check()
if(len(x)!=10):
print("Phone no should be 10 digits,re enter phone no")
return check()
return x
return check
@decor
def accept():
n=input("Enter your phone number:")
return n;
print("Entered Phone number is:",accept())
7. Write a program to find sum of the array elements, largest array element and
smallest element in the array.
from array import *
a=array('i',[])
n=int(input("Enter number of elements:"))
print("Enter array elements:")
for i in range(n):
a.append(int(input()))
sum=0
for i in range(n):
sum=sum+a[i]
large=small=a[0]
for i in range(1,n):
if large<a[i]:
large=a[i]
if small>a[i]:
small=a[i]
print("Array elements are:")
for i in range(n):
print(a[i],end=" ")
print()
print("Sum of array elements:",sum)
print("Largest element in the array:",large)
print("Smallest element in the array:",small)
Dept of C.Sc NCB Python Lab Programs Page 3
8. Program to find sum, difference and product of two matrices and also find
transpose of first matrix.
from numpy import *
n=int(input("Enter size of the array(nxn):"))
print("Enter the first matrix")
a=matrix([[input() for j in range(n)] for i in range(n)],int)
print("Enter the second matrix")
b=matrix([[input() for j in range(n)] for i in range(n)],int)
print("First Matrix is:")
print(a)
print("Second Matrix is:")
print(b)
print("Sum of the Matrices:",)
print(a+b)
print("Difference of the Matrices:",)
print(a-b)
print("Product of the Matrices:",)
print(a*b)
print("Transpose of first Matrix:",)
print(a.transpose())
9. Write a program to add name and scores of players into two separate lists and make
them into dictionary using zip function. Also retrieve runs by entering the player’s
name.
name=[]
score=[]
n=int(input("Enter How many players? "))
for i in range(0,n):
name.append(input("Enter Player name:"))
score.append(input("Enter score:"))
z=zip(name,score)
d=dict(z)
print(d)
name=input("Enter name of player for score: ")
print("The Score is",d[name])
10. Write a program to create class employee with instance variables eid, ename and
esalary. Accept and display n employees details.
class Employee:
def __init__(self,id,name,sal):
self.eid=id
self.ename=name
self.esal=sal
Dept of C.Sc NCB Python Lab Programs Page 4
def display(self):
print("Emp-id:",self.eid)
print("Emp-Name:",self.ename)
print("Emp-Salary:",self.esal)
e=[]
n=int(input("Enter number of employees:"))
for i in range(1,n+1):
print("Enter emp-id,name and salary of Employee-",i)
e.append(Employee(int(input()),input(),float(input())))
i=1
for obj in e:
print("Employee-",i,"information")
obj.display()
i=i+1
11. Write a program to demonstrate multilevel inheritance.
class grandfather:
def __init__(self,gn):
self.gname=gn
def display1(self):
print("I am grandfather, My Name is:",self.gname)
class father(grandfather):
def __init__(self,fn,gn):
self.fname=fn
super().__init__(gn)
def display2(self):
print("I am father, My Name is:",self.fname)
class child(father):
def __init__(self,cn,fn,gn):
self.cname=cn
super().__init__(fn,gn)
def display3(self):
print("I am child, My Name is:",self.cname)
c=child("Lava","Rama","Dasharatha")
c.display1()
c.display2()
c.display3()
Dept of C.Sc NCB Python Lab Programs Page 5
12. Write a program to demonstrate abstract class, abstract method and
overriding of abstract method.
from abc import ABC, abstractmethod
class Polygon(ABC):
@abstractmethod
def noofsides(self):
pass
class Triangle(Polygon):
def noofsides(self):
print("I have 3 sides")
class Pentagon(Polygon):
def noofsides(self):
print("I have 5 sides")
class Hexagon(Polygon):
def noofsides(self):
print("I have 6 sides")
class Rectangle(Polygon):
def noofsides(self):
print("I have 4 sides")
T = Triangle()
T.noofsides()
P = Pentagon()
P.noofsides()
H = Hexagon()
H.noofsides()
R=Rectangle()
R.noofsides()
Dept of C.Sc NCB Python Lab Programs Page 6
13. Write a program to demonstrate user defined exception.
class MyException(Exception):
def init (self, arg):
self.msg = arg
def check(dict):
for k,v in dict.items():
print ("Name=",k,"Balance=",v)
if v<2000.00:
raise MyException("Balance amount is less in the account of "+k)
n=int(input("Enter number of Customers:"))
bank={input("Enter Name:"):int(input("Enter Balance:")) for i in range(n)}
try:
check(bank)
except MyException as me:
print (me)
14. Write a program to find occurrence of each word and number of lines
present in a file.
fname = input('Enter the file name: ')
try:
fhand = open(fname)
counts = dict()
i=0
for line in fhand:
i=i+1
words = line.split()
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
print(“ Occurrences of each word:”)
print(counts)
print("Number of lines present in the file:",i)
except:
print('File cannot be opened:', fname)
Dept of C.Sc NCB Python Lab Programs Page 7
15. Write GUI program to add two numbers by using tkinter module.
from tkinter import *
def add_numbers():
res=int(e1.get())+int(e2.get())
label_text.set(res)
window = Tk()
label_text=StringVar();
Label(window, text="Enter First Number:").grid(row=0, sticky=W)
Label(window, text="Enter Second Number:").grid(row=1, sticky=W)
Label(window, text="Result of Addition:").grid(row=3, sticky=W)
result=Label(window, text="", textvariable=label_text).grid(row=3,column=1,
sticky=W)
e1 = Entry(window)
e2 = Entry(window)
e1.grid(row=0, column=1)
e2.grid(row=1, column=1)
b = Button(window, text="Calculate", command=add_numbers)
b.grid(row=0, column=2,columnspan=2, rowspan=2,sticky=W+E+N+S, padx=5,
pady=5)
mainloop()
Dept of C.Sc NCB Python Lab Programs Page 8