Aryan Python 2022578
Aryan Python 2022578
Practical File
PYTHON LAB FILE
BTCS-513-18
Bachelor of Technology
(Computer Science & Engineering)
if(a>b):
if(a>c):
print(a,"is largest")
else:
print(c,"is largest")
elif(b>c):
print(b,"is largest")
else:
print(c,"is largest")
2. Write a program to determine whether a year is leap or not.
if(y%100==0):
if(y%400==0):
print("Leap year")
else:
print("Not leap year")
elif(y%4==0):
print("Leap year")
else:
print("Not leap year")
3. Write a program to determine whether a number is even or odd.
if(a%2==0):
print(a,"is even number")
else:
print(a,"is odd number")
4. Write a program to determine whether a triangle is isosceles or not?
d= b**2-4*a*c
if(d>=0):
root1= (-b+d**0.5)/2*a
root2= (-b-d**0.5)/2*a
#program to print numbers upto N which are not divisible by 3,6 and 9
N=int(input("Enter N "))
print("Table for",a,":")
for i in range(1,11):
print(a,"x",i,"=",a*i)
8. Write a program to compute sum of first n natural numbers.
n= int(input("Enter n "))
sum=0
for i in range (1,n+1):
sum=sum+i
print("Sum of first",n,"natural numbers is",sum)
9. Write a program that prompts a number from the user and generates the Fibonacci
sequence upto that number. The Fibonacci sequence is given as under: 0 1 1 2 3 5 8 13 21 43
…
#program that prompts a number from the user and generates the Fibonacci sequence upto that
number. The Fibonacci sequence is given as under: 0 1 1 2 3 5 8 13 21 43 …
#program that prompts the user for an integer number and then prints all its factors.
for i in range(r):
if a[i]!=a[j]:
flag=1
break
j-=1
if (flag==1):
print(num,"is not a palindrome")
else:
print(num,"is a palindrome")
12. Write a program to determine whether a number is prime or not.
astring= str(a)
length=len(astring)
sum= 0
for i in range(length):
sum= sum+ int(astring[i])**length
if(a==sum):
print(a,"is an Armstrong number")
else:
print(a,"is not an Armstrong number")
14. Write a program to reverse the digits of a number.
while(t>0):
rev= rev*10 +(t%10)
t= t//10
print(rev)
15. Write a program to compute HCF of a number input by the user.
for i in range(1,min(a,b)+1):
if(a%i==0 and b%i==0):
hcf= i
print("HCF of",a,"and",b,"is",hcf)
16. Write a program to read n integer numbers interactively and print the biggest and
smallest numbers.
#program to read n integer numbers interactively and print the biggest and smallest numbers
for i in range(n):
t= int(input())
a.append(t)
maxi= a[0]
mini= a[0]
for i in range(1,n):
if(a[i]<mini):
mini= a[i]
if(a[i]>maxi):
maxi= a[i]
print("Maximum",maxi)
print("Minimum",mini)
Lab Assignment 2
1. Write a program to compute the area of the following two dimensional shapes
a. Circle
b. Triangle
c. Rectangle
d. Square
e. Trapezoid
f. Sphere
g. Parallelogram
while(1):
print("Enter your choice")
print("a-Circle b-Triangle c-Rectangle d-Square e-Trapezoid f-Sphere g-Parallelogram
h-Exit program ")
choice= input()
if(choice=='h'):
break
elif (choice=='a'):
r=int(input("Enter radius of circle "))
area= 3.14*r**2
print("Area of circle is",area)
elif (choice=='b'):
b= int(input("Enter base of triangle "))
h= int(input("Enter height of triangle "))
area= 0.5*b*h
print("Area of circle is",area)
elif(choice=='c'):
l= int(input("Enter length of triangle "))
b= int(input("Enter breadth of triangle "))
area= l*b
print("Area of rectangle is",area)
elif(choice=='d'):
s= int(input("Enter side of square "))
area= s**2
print("Area of square is",area)
elif(choice=='e'):
a= int(input("Enter short base of trapezoid "))
b= int(input("Enter long base of trapezoid "))
h= int(input("Enter height of trapezoid "))
area= ((a+b)*h)//2
print("Area of trapezoid is",area)
elif(choice=='g'):
b= int(input("Enter base of parallelogram "))
h= int(input("Enter height of parallelogram"))
area= b*h
print("Area of parallelogram is",area)
else:
print("Invalid choice")
print("exit")
2. Write a program to compute volume of the following three dimensional shapes
a. Cube
b. Cylinder
c. Cone
while(1):
print("Enter your choice ")
print("a-Cube b-Cylinder c-Cone d-Exit")
choice= input()
if(choice=='a'):
side= int(input("Enter side of cube "))
volume= side**3
print("Volume of cube is",volume)
elif(choice=='b'):
radius= int(input("Enter radius of cylinder "))
height= int(input("Enter height of cylinder "))
volume= 3.14*radius**2*height
print("Volume of cylinder is",volume)
elif(choice=='c'):
radius= int(input("Enter radius of cone "))
height= int(input("Enter height of cone "))
volume= (3.14*radius**2*height)/3
print("Volume of cone is",volume)
elif(choice=='d'):
break
else:
print("Invalid choice")
print("Exit")
3. Write a program that input data for a Python list. Then compute and print the sum and
average of entered numbers.
'''program that input data for a Python list. Then compute and print the sum and average of entered
numbers'''
l1=[]
n= int(input("Enter size of list "))
s= 0
for i in l1:
s=s+i
print("Sum",s)
print("Average",s/n)
4. Write a program to input 10 numbers. Then compute and display the sum of even numbers
and product of odd numbers.
'''program to input 10 numbers. Then compute and display the sum of even numbers and product of
odd numbers'''
s= 0
p= 1
for i in range(10):
a= int(input("Enter number "))
if(a%2==0):
s=s+a
else:
p=p*a
print("Sum",s)
print("Product",p)
5. Write a program to count the occurrence of a digit 5 in a given integer number.
astr= str(a)
print(astr)
count= 0
for i in range(len(astr)):
if(int(astr[i])==b):
count+=1
print(b,"occours",count,"times in",a)
6. Write a program to compute the factorial of a number.
fac= a
t= a
while(t>1):
t-=1
fac= fac*t
print("Factorial of",a,"is",fac)
7. Write a program to generate prime numbers in a certain range input by the user.
if(i==0 or i==1):
flag= 1 #0 and 1 are not prime
for j in range(2,i//2+1):
if(i%j==0):
flag= 1
break
if(flag==0):
print(i,end=" ")
8. Write a program to calculate and display Geometric and Harmonic means.
l1=[]
for i in range(n):
t= int(input("Enter element "))
l1.append(t)
#geometric mean
gm= 1
for i in l1:
gm*= i
gm= gm**(1/n)
#harmonic mean
hm= 0
for i in l1:
hm+= 1/i
hm= n/hm
print("Geometric mean",gm)
print("Harmonic mean",hm)
9. Write a program to convert a decimal number into its binary equivalent and vice versa.
'''program to convert decimal number into its binary equivalent and vice versa'''
def decimal_binary(a):
i= a
ar=[]
while(i>=1):
x= i%2
ar.append(x)
i=i//2
ar.reverse()
for i in ar:
print(i,end="")
def binary_decimal(b):
i= b
j= 0
ans= 0
while(i>0):
ans= ans+ (i%10)*2**j
j+= 1
i=i//10
print(ans)
while(1):
print("\nEnter your choice as a or b")
print("a->Decimal to binary")
print("b->Binary to decimal")
print("c->Exit")
choice= input()
if (choice=='a'):
x= int(input("Enter a decimal number "))
decimal_binary(x)
elif(choice=='b'):
x=int(input("Enter a binary number "))
binary_decimal(x)
elif(choice=='c'):
print("Exit")
break
else:
print("Invalid choice")
10. Write a program to print all the possible combinations of 4,5 and6.
ar=[4,5,6]
for i in range(3):
for j in range(3):
for k in range(3):
if(i!=j and i!=k and j!=k):
print(ar[i],ar[j],ar[k])
Lab Assignment 3
def si(p,r,t):
s= (p*r*t)/100
return s
def ci(p,r,t):
c= p*pow((1+r/100),time)- p
return c
simple_interest= si(principle,rate,time)
compound_interest= ci(principle,rate,time)
def add(x,y):
return x+y
def subtract(x,y):
return x-y
def multiply(x,y):
return x*y
def divide(x,y):
return x/y
while(1):
a= int(input("Enter first number "))
b= int(input("Enter second number "))
def totalsum(n):
return n*(n+1)/2
def fibonacci(n):
prev= 1
fib= 0
for i in range(n):
print(fib,end=" ")
prev,fib= fib,fib+prev
def check(a):
if(a<2):
return 0
for i in range(2,a//2+1):
if(a%i==0.0):
return 0
return 1
def check(a):
if(a<2):
return 0
for i in range(2,a//2+1):
if(a%i==0.0):
return 0
return 1
def print_interval(x,y):
for i in range(x,y):
if(check(i)):
print(i,end=" ")
def mean(ar):
s= 0
for i in ar:
s= s+ i
s= s/len(ar)
return s
def variance(ar):
s= 0
for i in ar:
s= s+ (pow(i-mean(ar),2))/len(ar)
return s
def standard_deviation(ar):
s= pow(variance(ar),0.5)
return s
values= []
m= mean(values)
v= variance(values)
sd= standard_deviation(values)
print("Mean ",m)
print("Variance ",v)
print("Standard deviation ",sd)
8. Write a program to compute factorial of a number.
def fact(x):
if(x==0 or x==1):
return 1
else:
f= x* fact(x-1)
return f
ans= fact(a)
print("Factorial of",a,"is",ans)
9. Write a program to print a multiplication table.
def mul_table(x):
for i in range(1,11):
print(x," x ",i," = ",x*i)
mul_table(n)
10. Write a program to compute sum of A.P series.
def sum_ap(a,d,n):
s= (n/2) *(2*a + (n-1)*d)
return s
ans= sum_ap(first,difference,num)
def sum_gp(a,r,n):
if(r<1):
s= (a*(1-pow(r,n)))/(1-r)
else:
s= (a*(pow(r,n)-1))/(r-1)
return s
ans= sum_gp(first,ratio,num)
def sum_hp(n):
s= 0
for i in range(1,n+1):
s= s+ 1/i
return s
def triangle():
b= int(input("Enter base of triangle "))
h= int(input("Enter height of traingle "))
a= 0.5*b*h
return a
def circle():
r= int(input("Enter radius "))
a= 3.14*r*r
return a
def rhombus():
d1= int(input("Enter diagonal 1 "))
d2= int(input("Enter diagonal 2 "))
a= d1*d2*0.5
return a
def parallelogram():
b= int(input("Enter base "))
h= int(input("Enter height "))
a= b*h
return a
while(1):
print("Enter your choice")
print("a-Triangle b-Circle c-Rhombus d-Parallelogram e-Exit program ")
choice= input()
if(choice=='e'):
break
elif (choice=='a'):
ans= triangle()
print("Area of triangle ",ans)
elif (choice=='b'):
ans= circle()
print("Area of circle ",ans)
elif (choice=='c'):
ans= rhombus()
print("Area of rhombus ",ans)
elif (choice=='d'):
ans= parallelogram()
print("Area of parallelogram ",ans)
else:
print("Invalid choice")
print("END")
Lab Assignment 4
def fact(x):
if(x==0 or x==1):
return 1
else:
f= x* fact(x-1)
return f
def exp1(x,n):
ans= 0
j= 0
for i in range(1,n+1,2):
ans+= pow(x,i)*pow(-1,j)/fact(i)
j+=1
return ans
def exp2(x,n):
ans= 0
for i in range(1,n+1):
ans+= pow(x,i)*pow(-1,i+1)/fact(i)
return ans
call_exp1= exp1(xm,nm)
call_exp2= exp2(xm,nm)
import calendar
def cal(year,month):
print("\n",calendar.month(year,month))
cal(yy,mm)
3. Write a program to shuffle a deck of cards.
import random
import itertools
def shuffle_cards(cards):
random.shuffle(cards)
def draw_cards(cards):
for i in range(5):
print(cards[i][0]," of",cards[i][1])
print()
deck= list(itertools.product(['Ace',2,3,4,5,6,7,8,9,10,'Jack','Queen','King'],
['Spade','Heart','Diamond','Club']))
shuffle_cards(deck)
draw_cards(deck)
#program to convert decimal number to equivalent binary, octal, and hexadecimal numbers
def decimal_binary(x):
i= x
ar=[]
while(i>=1):
x= i%2
ar.append(x)
i=i//2
ar.reverse()
ans= 0
for i in ar:
ans= ans*10+i
return ans
def decimal_octal(x):
i= x
ar=[]
while(i>=1):
x= i%8
ar.append(x)
i=i//8
ar.reverse()
ans= 0
for i in ar:
ans= ans*10+i
return ans
b= decimal_binary(num)
o= decimal_octal(num)
h= hex(num) #built-in function, bin() and oct() can be used too
print("Decimal",num)
print("Binary",b)
print("Octal",o)
print("Hexadecimal",h.lstrip("0x")) #lstrip("0x") removes "0x" from left
5. Write a program to print ASCII value of a string.
def ascii_string(s):
for i in s:
print(i,":",ord(i))
class test:
f=0
prev= 1
def fib(n):
if(n):
print(test.f,end= ' ')
test.f,test.prev=test.f+test.prev,test.f
test.fib(n-1)
else:
return 1
def GCD(x,y):
if(x==y):
return x
else:
if(x>y):
return GCD(x-y,y)
else:
return GCD(x,y-x)
'''
algorithm
move n-1 disks from source to helper
move nth disk from source to destination
move n-1 disks from helper to destination
'''
def Hanoi(disk,source,dest,helper):
if(disk==1):
print("Move disk",disk,"from",source,"to",dest)
else:
Hanoi(disk-1,source,helper,dest)
print("Move disk",disk,"from",source,"to",dest)
Hanoi(disk-1,helper,dest,source)
def myfunc(n):
return lambda a: a**n
square= myfunc(2)
cube= myfunc(3)
print("Square of",x,"is",square(x))
print("Cube of",x,"is",cube(x))
1. Create a module of factorial, which can be called both in script and interpreter mode.
ans= fact(a)
print("Factorial of",a,"is",ans)
2. Create a module of fibonacci series, which can be called both in script and interpreter
mode.
#module of fibonacci series, which can be called both in script and interpreter mode
fib(a)
3. Write a program to evaluate the following expressions using functions/modules.
1. Write a program to create a class BankAccount, which contains the data members
account_number, customer_name, account_type, balance and class methods deposit(),
withdraw(), ans summary().
Include an option that user can withdraw a maximum anount of rupees 10000/- per
transaction and the balance must meet the minimum balance amount of rupees 1000/- in the
account.
#assignment 6, q1
class BankAccount:
def __init__(self,account_number,customer_name,account_type):
self.account_number= account_number
self.customer_name= customer_name
self.account_type= account_type
self.balance= 0
def deposit(self):
amount= float(input("Enter the deposit amount "))
self.balance+= amount
print("Amount deposited successfully")
print("\n")
def withdraw(self):
amount= float(input("Enter the withdraw amount "))
if((self.balance-amount)<1000 ):
print("Insufficient balance")
else:
if(amount>10000):
print("Sorry, can't withdraw more than 10000, please try again with a
lesser amount")
else:
self.balance-= amount
print("Amount withdrawn successfully")
print("\n")
def summary(self):
print("Account number : ",self.account_number)
print("Name : ",self.customer_name)
print("Account type : ",self.account_type)
print("Current balance : ",self.balance)
print("\n")
a1= BankAccount(1,"Kushal","Savings")
a1.summary()
a1.deposit()
a1.summary()
a1.withdraw()
a1.summary()
2. Write a program to create a class Employee containing the data members emp_name,
emp_ID, Dept, basic_pay, HRA, DA, MA with member functions total_salary() [computes the
total salary based on basic pay, HRA=20% of basic_pay, DA=120% of basic_pay, and
MA=5% of basic_pay] and emp_details, displays the complete details of the employee.3. Write
a program to create a class Electricity_bill with data members bill_id, customer_name,
meter_no, no_of_units, total_amount, previous_balance and member functions
compute_bill(), which computes the monthly electricity bill based on the following criteria:
Units Cost per unit (Rs.)
200 5/-
200-400 7/-
400-800 10/-
800-1600 13/-
Above 1600 15/-
If the previous bill is not paid then previous bill along with penalty.
#assignment 6, q2
class employee:
def __init__(self,emp_name,emp_ID,dept,basic_pay):
self.emp_name= emp_name
self.emp_ID= emp_ID
self.dept= dept
self.basic_pay= basic_pay
self.hra= basic_pay* 0.2
self.da= basic_pay* 1.2
self.ma= basic_pay* 0.5
def total_salary(self):
gross_sal= self.basic_pay+ self.hra+ self.da+ self.ma
return gross_sal
def emp_details(self):
print("Employee details:\n")
print("Name : ",self.emp_name)
print("ID : ",self.emp_ID)
print("Department : ",self.dept)
print("Basic pay : ",self.basic_pay)
print("Total salary : ",self.total_salary())
print("\n")
e1= employee("Kushal",21,"Developer",20000)
e1.emp_details()
3. Write a program to create a class Electricity_bill with data members bill_id,
customer_name, meter_no, no_of_units, total_amount, previous_balance and member
functions compute_bill(), which computes the monthly electricity bill based on the following
criteria:
Units Cost per unit (Rs.)
200 5/-
200-400 7/-
400-800 10/-
800-1600 13/-
Above 1600 15/-
If the previous bill is not paid then previous bill along with penalty.
#assignment 6, q3
class electricity_bill:
def __init__(self,bill_id,customer_name,meter_no,no_of_units,previous_balance):
self.bill_id= bill_id
self.customer_name= customer_name
self.meter_no= meter_no
self.no_of_units= no_of_units
self.previous_balance= previous_balance
self.penalty= 500
self.total_amount= self.compute_bill()
def compute_bill(self):
if(self.no_of_units<200):
self.total_amount= 5* self.no_of_units
elif(self.no_of_units<400):
self.total_amount= 7* self.no_of_units
elif(self.no_of_units<800):
self.total_amount= 10* self.no_of_units
elif(self.no_of_units<1600):
self.total_amount= 13* self.no_of_units
else:
self.total_amount= 15* self.no_of_units
if(self.previous_balance<0):
self.total_amount+= self.penalty
self.total_amount-= self.previous_balance
return self.total_amount;
def display(self):
print("Electricity bill :\n")
print("Bill ID : ",self.bill_id)
print("Customer name : ",self.customer_name)
print("Meter number : ",self.meter_no)
print("Units : ",self.no_of_units)
print("Previous balance : ",self.previous_balance)
2. Write a program to input item details: name, price, quantity, code. Then compute the
invoice item wise and total bill. Display the result in proper format.
1. Write a program to illustrate the concept of overloading of arithmetic ‘+’ operator.
class distance():
'A distance class'
def __init__(self,km,m):
self.km= km
self.m= m
def __add__(self,obj):
km= self.km+ obj.km+ (self.m+ obj.m)//1000
m= (self.m+ obj.m)%1000
return distance(km,m)
def display(self):
print(self.km,"kms"," ",self.m,"m")
d1= distance(20,400)
d2= distance(2,600)
d3= d1+ d2 #d1.add(d2)
d1.display()
d2.display()
d3.display()
2. Write a program to illustrate the concept of overloading of biwise ‘&’ operator.
class number():
def __init__(self,num):
self.num= num
def __and__(self,obj):
num= self.num & obj.num
return number(num)
def ret(self):
return self.num
n1= number(12)
n2= number(20)
n3= n1 & n2 #n1.and(n2)
print(n1.ret(),"&",n2.ret(),"=",n3.ret())
3. Write a program to illustrate the concept of overloading of relational operator.
class distance():
'A distance class'
def __init__(self,km,m):
self.km= km
self.m= m
def __gt__(self,obj):
if(self.km> obj.km):
return True
elif(self.km< obj.km):
return False
else:
if(self.m> obj.m):
return True
else:
return False
def display(self):
print(self.km,"kms"," ",self.m,"m")
d1= distance(20,800)
d2= distance(20,90)
d1.display()
d2.display()
if(d1>d2): #d1.gt(d2)
print("First distance is greater ")
else:
print("First distance is not greater ")
Lab Assignment 7
1. Write a program to extract data using regular expressions of Python , where you have to
extract the number data from a text file and then compute sum of all the extracted numbers.
import re
f= open("text_file","r")
txt= f.read()
f.close()
nums= re.findall(r"\d+",txt)
summ= 0
for i in nums:
summ= summ+ int(i)
print("Sum of all numbers in given string is ",summ)
“text_file”
When you multiply a number by itself, you get its square.
Example, 2 * 2 is equal to 4 which is equals to 2 ^ 2.
Reading books is a good habit. This mean we all should read books in our free time.
For more simple facts you can contact me on the below mentioned phone number : 9017253579 .
2. Write a python program which matches a string that has been followed by “ing” from a line
of text , e.g. playing, reading, etc.
import re
f= open("text_file","r")
txt= f.read()
f.close()
ing= re.findall(r"\w+ing",txt)
import re
f= open("text_file","r")
txt= f.read()
f.close()
t= re.findall(r"\bt+\w+",txt)
print("Words starting with 't' in given text are : ",t)
4. Write a program that mathes all words containing ‘s’, at the end of the word.
import re
f= open("text_file","r")
txt= f.read()
f.close()
s= re.findall(r"\b\w+s",txt)
print("Words ending with 's' are : ",s)
5. Write a program that extract mobile number of 10 digits if exists from a string of text.
import re
f= open("text_file","r")
txt= f.read()
f.close()
num= re.findall(r"\b\d{10}",txt)
print("Phone numbers in given text are : ",num)
Lab Assignment 8
1. Design an interface using tkinter library of Python, which should include following
controls:
canvas,, frames, buttons, textbox, spin box, radio buttons, checkboxes, list box, scrollbar.
LAB ASSIGNMENT -8
Design an interface using tkinter library of Python, which should
include following controls:
canvas, frames, buttons, textbox, spinbox, radio buttons, checkboxes,
listbox, scrollbar.
window = Tk()
def onClick():
var = StringVar()
var.set("one")
cb = Combobox(window, values=data)
cb.place(x=60, y=150)
lb.insert(END, num)
lb.place(x=250, y=150)
v0 = IntVar()
v0.set(1)
r1.place(x=100, y=50)
r2.place(x=180, y=50)
v1 = IntVar()
v2 = IntVar()
C1.place(x=100, y=100)
C2.place(x=180, y=100)
window.title('Hello Python')
window.geometry("400x300+10+10")
btn.place(x=30,y=150)
btn.pack(anchor="sw")
btn=Button(window,text="Welcome",fg="black",bg="white")
btn.place(x=30,y=150)
window.mainloop()
Output: