0% found this document useful (0 votes)
91 views

Aryan Python 2022578

The document outlines a Python lab file submitted by a student named Aryan Kr. Choudhary to their instructor Dr. Pooja Sharma, containing 70 programming tasks related to Python concepts like conditional statements, loops, functions, modules, file handling, OOPs, inheritance and regular expressions that the student was assigned to complete.

Uploaded by

Fake ID
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
91 views

Aryan Python 2022578

The document outlines a Python lab file submitted by a student named Aryan Kr. Choudhary to their instructor Dr. Pooja Sharma, containing 70 programming tasks related to Python concepts like conditional statements, loops, functions, modules, file handling, OOPs, inheritance and regular expressions that the student was assigned to complete.

Uploaded by

Fake ID
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

I.K.

G Punjab Technical University, Kapurthala


Department of Computer Science Engineering

Practical File
PYTHON LAB FILE
BTCS-513-18

Bachelor of Technology
(Computer Science & Engineering)

Submitted To: Submitted By:


Dr. Pooja Sharma Name: Aryan Kr. Choudhary
Branch: BTech (CSE) 5th
Roll No: 2022578
Sr. No. Tasks Page No. Remarks
1. Write a program to print largest of three numbers using if-
else statement.
2. Write a program to determine whether a year is leap or not.

3. Write a program to determine whether a number is even or


odd.
4. Write a program to determine whether a triangle is isosceles
or not?
5. Write a program to find out the roots of a quadratic equation.

6. Write a program to print umbers upto n which are not


divisible by 3,6 and 9.
7. Write a program to print multiplication table.
8. Write a program to compute sum of first n natural numbers.
9. Write program that prompts a number from the user and
generates the Fibonacci sequence upto that number.
10. Write a program that prompts the user for an integer number
and then prints all its factors.
11. Write a program to determine whether a number is
palindrome or not.
12. Write a program to determine whether a number is prime or
not.
13. Write a program to determine an Armstrong number.
14. Write a program to reverse the digits of a number.
15. Write a program to compute HCF of a number input by the
user.
16. Write a program to read n integer number interactively and
print the biggest number.

17. 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
18. Write a program to compute volume of the following three
dimensional shapes
a. Cube
b. Cylinder
c. Cone
19. Write a program that input data for a Python list. Then
compute and print the sum and average of entered numbers.
20. Write a program to input 10 numbers. Then compute and
display the sum of even numbers and product of odd
numbers.
21. Write a program to count the occurrence of a digit 5 in a
given integer number.
22. Write a program to compute the factorial of a number.
23. Write a program to generate prime numbers in a certain
range input by the user.
24. Write a program to calculate and display Geometric and
Harmonic means.
25. Write a program to convert a decimal number into its binary
equivalent and vice versa.
26. Write a program to print all the possible combinations of 4,
5, and 6.
27. Write a program to compute simple and compound interest.

28. Write a program to design a simple calculator.


29. Write a program to compute sum of first N natural numbers.
30. Write a program to generate a Fibonacci series.
31. Write a program that determines whether a number is prime
or not.
32. Write a program to print prime numbers between certain
interval.
33 Write a program to compute mean, variance, and, standard
deviation.
34. Write a program to compute factorial of a number.
35. Write a program to print a multiplication table.
36. Write a program to compute sum of A. P. series.
37. Write a program to compute sum of G. P. series.
38. Write a program to compute sum of H. P. series.
39. Write a program to compute area of following shapes
a. Triangle
b. Circle
c. Rhombus
d. Parallelogram
40. Write a program to evaluate the following expressions (see
attachment)
41. Write a program to display a calendar.
42. Write a program to shuffle a deck of cards.
43. Write a program to convert decimal number to equivalent
binary, octal, and hexadecimal numbers
44. Write a program to print ASCII value of a string
45. Write a program to print Fibonacci series using recursion
46. Write a program to compute GCD using recursion.
47. Write a program to print tower of Hanoi using recursion.
48. Write a program to print day of a month
49. Write a program to illustrate the use of lambda function.
50. Create a module of factorial, which can be called both in
script and interpreter mode
51. Create a module of fibonacci series, which can be called both
in script and interpreter mode.
52. Write a program to evaluate the following expressions (see
attachment) using functions/modules
53. Write a program to open the file created in Program 1 and
compute the total marks and grade of all the students then
display and save total marks and grade along with Name,
RollNo, Marks, etc in the preexisting file
54. Write a program to a file named Invoice of purchased items
from a general store, which contains ItemNo, ItemName,
Price, Quantity. Compute the total_bill then display and save
the file along with preexisting data.
55. Write a program to create a file containing the information of
patients of a hospital with attributes PatientName, PatientID,
Age, Gender, Disease, Status(Cured or Not Cured) and
Contact Number.
56. Write a program to create a file exhibiting the data of a bank
account with details, CustomerName, AccountNo,
AccountType, Balance, and Contact Number.
57. Write a program to create a file containing the record of
employees with attributes Employee_Name, Emp_ID,
Department, Basic_Pay, Total_Salary
(Basic+DA+HRA+MA), where DA is 125% of Basic_Pay,
HRA is 20% of Basic_Pay, MA is 10% of Basic_Pay.
Compute the total salary and save the complete record of 10
employees in the file
58. 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(), and summary(). Include an option that
a user can withdraw a maximum amount of rupees 10000/-
per transaction and the balance must meet the minimum
balance amount of rupees 1000/- in the account
59. 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
60. Write a program to input students details and marks then
compute total marks and percentage and display the entire
result using the single, multiple, and multilevel inheritance.
61. 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.
62. Write a program to illustrate the concept of overloading of
arithmetic '+' operator.
63. Write a program to illustrate the concept of overloading of
bitwise '&' operator.
64. Write a program to illustrate the concept of overloading of
relational '>' operator. Also practice variants of arithmetic,
bitwise, and relational operators as taught in class.
65. 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.
66. Write a Python program which matches a string that has
been followed by "ing" from a line of text, e.g., playing,
reading, etc.
67. Write a program that matches all the words containing 't', at
the start of the word.
68. Write a program that matches all words containing 's', at the
end of the word.
69. Write a program that extract mobile number of 10 digits if it
exists from a string of text.
70. Design an interface using tkinter library of Python, which
should include following controls: canvas, frames, buttons,
textbox, spinbox, radio buttons, checkboxes, listbox,
scrollbar.
Lab Assignment 1

1. Write a program to print largest of three numbers using if-else statement.

#program to print largest of three numbers using if-else statement

print("Enter 3 numbers ")


a= int(input())
b= int(input())
c= int(input())

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.

#program to determine whether a year is leap or not

y=int(input("Enter year "))

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.

#program to determine a number is even or not

a= int(input("Enter number "))

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?

#program to determine whether a trinagle is isosceles or not

print("Enter length of 3 sides of trianlge ")


a= int(input())
b= int(input())
c= int(input())

if(a==b or a==c or b==c):


print("Entered triangle is isosceles")
else:
print("Entered triangle is not isosceles")
5. Write a program to find out the roots of a quadratic equation.

#program to find roots of a quadratic equation

print("Let quadratic equation be a.x^2+b.x+c=0, enter a,b,c ")


a= int(input())
b= int(input())
c= int(input())

d= b**2-4*a*c
if(d>=0):
root1= (-b+d**0.5)/2*a
root2= (-b-d**0.5)/2*a

print("Roots of equation",a,"x^2+",b,"x+",c,"=0 are",root1,"and",root2)


else:
print("Roots don't exist")
6. Write a programs to print numbers upto N which are not divisible by 3,6 and 9, e.g.,
1,2,4,7,...

#program to print numbers upto N which are not divisible by 3,6 and 9

N=int(input("Enter N "))

for i in range (N):


if(i%3!=0):
print(i,end=' ')
7. Write a program to print multiplication table.

#program to print multiplication table

a= int(input("Enter a number "))

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.

#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 …

n=int(input("Enter a number "))


fib= 0
prev= 1
for i in range (n):
print(fib,end=' ')

prev,fib= fib,fib + prev


10. Write a program that prompts the user for an integer number and then prints all its
factors.

#program that prompts the user for an integer number and then prints all its factors.

a= int(input("Enter a number "))


r= a//2

print("Factors of",a,"are ",end=' ')


for i in range(1,r+1):
if(a%i==0):
print(i,end=',')
print(a)
11. Write a program to determine whether a number is palindrome or not.

#program to determine whether a number is palindrome or not

num= int(input("Enter a number "))


a= str(num)
j= len(a)-1
flag= 0
r=len(a)//2+1 #range

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.

#program to determine whether a number is prime or not

a= int(input("Enter a number "))


flag= 0 #flag=1 means is not prime

if(a==0 or a==1): #0 and 1 are not prime


flag=1

for i in range (2,a//2+1):


if(a%i==0):
flag=1
break
if(flag==1):
print(a,"is not prime")
else:
print(a,"is prime")
13. Write a program to determine an Armstrong number.

#program to determine an Armstrong number

a= int(input("Enter a number "))

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.

#program to reverse the digits of a number

a= int(input("Enter a number "))


t= a
rev= 0

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.

#program to compute HCF of a number input by the user

a= int(input("Enter first number "))


b= int(input("Enter second number "))

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

n= int(input("How many numbers you want to input "))


print("Enter",n,"numbers")
a=[]

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

'''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
h. Exit program'''

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

'''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 "))

for i in range (n):


a= int(input("Enter element "))
l1.append(a)

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.

'''program to count the occurrence of a digit 5 in a given integer number'''

a= int(input("Enter number "))


b= int(input("Enter digit whose count you want to find "))

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.

#program to compute the factorial of a number

a= int(input("Enter 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.

#program to generate prime numbers in a certain range input by the user

print("Enter a and b for range (a,b)")


a= int(input())
b= int(input())

print("Prime numbers in range(",a,",",b,")")


for i in range(a,b):
flag= 0

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.

#program to calculate and display Geometric and Harmonic means

n= int(input("Enter number of elements "))

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.

'''program to print all the possible combinations of 4,5 and 6'''

#program to print all the possible combination of 4,5 and 6

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

1. Write a program to compute simple and compound interest.

#program to compute simple and compound interest

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

principle= int(input("Enter principle "))


rate= float(input("Enter rate "))
time= int(input("Enter time "))

simple_interest= si(principle,rate,time)
compound_interest= ci(principle,rate,time)

print("Simple interest ",simple_interest)


print("Compound interest ",compound_interest)
2. Write a program to design a simple calculator.

#program to design a simple calculator

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 "))

print("Enter your choice ")


print("a->ADD b->SUBTRACT c->MULTIPLY d->DIVIDE e->EXIT")
choice= input()
if(choice=='a'):
ans= add(a,b)
print (ans)
elif(choice=='b'):
ans= subtract(a,b)
print (ans)
elif(choice=='c'):
ans= multiply(a,b)
print (ans)
elif(choice=='d'):
ans= divide(a,b)
print(ans)
elif(choice=='e'):
print("END")
break
else:
print("Invalid choice")
3. Write a program to compute sum of first N natural numbers.

#program to compute sum of first N natural numbers

def totalsum(n):
return n*(n+1)/2

num= int(input("Enter n "))


ans= totalsum(num)

print("Sum of first",num,"natural numbers is",ans)


4. Write a program to generate a Fibonacci series.

#program to generate a Fibonacci series

def fibonacci(n):
prev= 1
fib= 0
for i in range(n):
print(fib,end=" ")

prev,fib= fib,fib+prev

l= int(input("Enter the length of fibonacci series "))


fibonacci(l)
print()
5. Write a program that determines whether a number is prime or not.

#program that determines whether a number is prime or not

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

b= int(input("Enter number "))


if(check(b)):
print(b,"is prime")
else:
print(b,"is not prime")
6. Write a program to print prime numbers between certain interval.

#program to print prime numbers between certain interval

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=" ")

start= int(input("Enter x for range (x,y) "))


end= int(input("Enter y for range (x,y) "))

print("Prime numbers in given range are ",end="")


print_interval(start,end)
print()
7. Write a program to compute mean, variance, and standard deviation.

#program to compute mean variance and standard deviation

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= []

n= int(input("Enter total number of values "))


for i in range(n):
print("Enter value",i," :",end=" ")
x=int(input())
values.append(x)

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.

#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

a= int(input("Enter number whose factorial you want to calculate "))

ans= fact(a)

print("Factorial of",a,"is",ans)
9. Write a program to print a multiplication table.

#program to print a multiplication table.

def mul_table(x):
for i in range(1,11):
print(x," x ",i," = ",x*i)

n= int(input("Enter a number "))

mul_table(n)
10. Write a program to compute sum of A.P series.

#program to compute sum of A.P series

def sum_ap(a,d,n):
s= (n/2) *(2*a + (n-1)*d)
return s

first = int(input("Enter first term of A.P "))


difference= int(input("Enter common difference "))
num= int(input("Enter number of terms "))

ans= sum_ap(first,difference,num)

print("Given A.P is ",end=" ")


for i in range(1,num+1):
print(first+(i-1)*difference,end=" ")
print()

print("Sum of given A.P is ",ans)


11. Write a program to compute sum of G.P series.

#program to compute sum of G.P series

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

first = int(input("Enter first term of G.P "))


ratio= float(input("Enter common ratio "))
num= int(input("Enter number of terms "))

ans= sum_gp(first,ratio,num)

print("Given G.P is ",end=" ")


for i in range(num):
print(first*pow(ratio,i),end=" ")
print()

print("Sum of given G.P is ",ans)


12. Write a program to compute sum of H.P series.

#program to compute sum of H.P series

def sum_hp(n):

s= 0
for i in range(1,n+1):
s= s+ 1/i
return s

num= int(input("Enter length of H.P "))


ans= sum_hp(num)

print("Sum of given H.P is ",ans)


13. Write a program to compute area of following shapes
a. Triangle
b. Circle
c. Rhombus
d. Parallelogram

#program to compute area of triangle, circle, rhombus, parallelogram

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

1. Write a program to evaluate the following expressions

#program to evaluate expressions

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

xm= int(input("Enter x ")) #x in main


nm= int(input("Enter n ")) #n in main

call_exp1= exp1(xm,nm)
call_exp2= exp2(xm,nm)

print("Sum of expression 'a' is",call_exp1)


print("Sum of expression 'b' is",call_exp2)
2. Write a program to display a calendar.

#program to display a calendar

import calendar

def cal(year,month):
print("\n",calendar.month(year,month))

yy= int(input("Enter year "))


mm= int(input("Enter month "))

cal(yy,mm)
3. Write a program to shuffle a deck of cards.

#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)

print("After shuffling we draw 5 cards again\n")


shuffle_cards(deck)
draw_cards(deck)
4. Write a program to convert decimal number to equivalent binary, octal, and hexadecimal
numbers.

#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

num= int(input("Enter a decimal number "))

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.

#program to print ASCII value of a string

def ascii_string(s):
for i in s:
print(i,":",ord(i))

str= input("Enter a string ")


ascii_string(str)
1. Write a program to print Fibonacci series using recursion.

#program to print Fibonacci series using recursion

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

x= int(input("Enter number of elements "))


test.fib(x)
print("\n")
2. Write a program to compute GCD using recursion.

#program to compute GCD using recursion

def GCD(x,y):
if(x==y):
return x
else:
if(x>y):
return GCD(x-y,y)
else:
return GCD(x,y-x)

a= int(input("Enter first number "))


b= int(input("Enter second number "))

print("Greatest common divisor is ",GCD(a,b))


3. Write a program to print tower of Hanoi using recursion.

#program to print tower of hanoi using recursion

'''
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)

n= int(input("Enter number of disks "))


Hanoi(n,'Source','Destination','Helper')
4. Write a program to print day of a month.
5. Write a program to illustrate the use of lambda function.

#program to illustrate the use of lambda function.

def myfunc(n):
return lambda a: a**n

square= myfunc(2)
cube= myfunc(3)

x= int(input("Enter number "))

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.

from mymodule import fact

a= int(input("Enter number "))

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

from mymodule import fib

a= int(input("Enter number of elements in finonacci series "))

fib(a)
3. Write a program to evaluate the following expressions using functions/modules.

# program to evaluate the following expressions using functions/modules

from mymodule import exp1,exp2

x= int(input("Enter value of x "))


n= int(input("Enter value of n "))
print("")
print("Sum of expression 'a' is ",exp1(x,n))
print("Sum of expression 'b' is ",exp2(x,n),"\n")
Lab Assignment 5
Lab Assignment 6

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)

print("Total amount :",self.total_amount)


eb1= electricity_bill(1555,"Kushal Pal",1222,1600,-1000)
eb1.display()
1. Write a program to input students details and marks then compute total marks and
percentage and display the entire result using the single, multiple, and multilevel inheritance.

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.

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

#program to illustrate the concept of overloading of bitwise '&' 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.

#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)

print("Words ending with 'ing' in given text are : ",ing)


3. 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()

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.

from tkinter import *

from tkinter import messagebox

from tkinter.ttk import Combobox

window = Tk()

def onClick():

messagebox.showinfo("Python","Thank you for using tkinter")

click1 = Button(window,text = "Click OK", command = onClick).place(x= 100, y=240)

var = StringVar()

var.set("one")

data = ("one", "two", "three", "four")

cb = Combobox(window, values=data)

cb.place(x=60, y=150)

lb = Listbox(window, height=5, selectmode='multiple')

for num in data:

lb.insert(END, num)

lb.place(x=250, y=150)

v0 = IntVar()

v0.set(1)

r1 = Radiobutton(window, text="CSE", variable=v0, value=1)

r2 = Radiobutton(window, text="EE", variable=v0, value=2)

r1.place(x=100, y=50)

r2.place(x=180, y=50)

v1 = IntVar()

v2 = IntVar()

C1 = Checkbutton(window, text="Cricket", variable=v1)

C2 = Checkbutton(window, text="Tennis", variable=v2)

C1.place(x=100, y=100)

C2.place(x=180, y=100)

window.title('Hello Python')

window.geometry("400x300+10+10")

btn=Button(window,text="This is created by ARYAN",fg="black",bg="white")

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:

You might also like