Ge3171-Python Lab
Ge3171-Python Lab
Ge3171-Python Lab
REGULATION 2021
GE3171 PROBLEM SOLVING AND
PYTHON PROGRAMMING LABORATORY
MANUAL REGULATION 2021
GE3171 PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY LTP C 0042
COURSEOBJECTIVES:
TOTAL:60 PERIODS
COURSEOUTCOMES:
On completion of the course, students will be able to:
CO1: Develop algorithmic solutions to simple computational problems.
CO2: Develop and execute simple Python programs.
CO3: Implement programs in Python using conditionals and loops for solving problems.
CO4: Deploy functions to decompose a Python program.
CO5: Process compound data using Python data structures.
CO6: Utilize Python packages in developing software applications.
List of Experiments
S.No List of Experiments
1a Electricity Billing
1c Sin Series
1d Weight of a Motorbike
3a Number Series
3b Number Patterns
3c Pyramid Pattern
6a Factorial
6c Area of shape
7a Reverse
7b Palindrome
7c Character count
7d Replacing characters
8a Numpy
8b Pandas
8c Matplotlib
8d Scipy
11 Exploring pygame
Aim
To write a python program for the Electricity Billing.
Algorithm
Step1: Start the program
Step2: Read the input variable “unit”
Step3: Process the following
When the unit is lessthanorequalto100units, calculate usage=unit*5
When the unit is between100to200units, calculate usage=(100*5)+((unit-100)*7)
When the unit is between 200 to 300 units, calculate usage=(100*5)+(100*7)+((unit-
200)*10)When the unit is above 300 units, calculate usage=(100*5)+(100*7)+(100*!0)+((unit-
300)*15)For further, no additional charge will be calculated.
Step4: Display the amount “usage” to the user.
Step5: Stop the program
Flowchart
Program
#program for calculating electricity bill in Python
units=int(input("please enter the number of units you consumed in a month"))
if(units<=100):
payAmount=units*1.5
fixedcharge=25.00
elif(units<=200):
payAmount=(100*1.5)+(units-100)*2.5
fixedcharge=50.00
elif(units<=300):
payAmount=(100*1.5)+(200-100)*2.5+(units-200)*4
fixedcharge=75.00
elif(units<=350):
payAmount=(100*1.5)+(200-100)*2.5+(300-200)*4+(units-300)*5
fixedcharge=100.00
else:
payAmount=0
fixedcharge=1500.00
Total=payAmount+fixedcharge;
print("\nElecticity bill=%.2f" %Total)
Output
in a month : 300
Electicity bill=875.00
Result
Thus the Electricity Billing program has been executed and verified successfully.
Ex.No:1.b
Date: Retail Shop Billing
Aim
To write a python program for the Retail Shop Billing.
Algorithm
Step1: Start the program
Step2: Initialize the values of the items
Step3: Read the input like the name of item and quantity.
Step 4: Process the following amount= (item_name *quantity) + amount
if(item==1):
amount = (soap*quantity)+
amount elif(item==2):
amount = (powder*quantity)+amount
elif(item==3):
amount = ( tooth_brush * quantity) +
amount elif(item==4):
amount=(paste*quantity)+amount
elif(item==5):amount=(perfume*quantity
)+amount
else:
print("Item Not available")
2. Powder
3. Tooth Brush
4. Tooth Paste
5. Perfume
To stop the shopping type number
0 Enter the item number: 1
Enter the quantity: 5
Enter the item number:
2 Enter the quantity: 4
Enter the item number: 0
Total amount need to pay is: 780
Happy for your visit
Result
Thus the Retail Shopping Billing program has been executed and verified successfully
Ex.No:1.c
Date : Sin Series
Aim
To write a python program for sin series.
Algorithm
Step1: Start the program.
Step2: Read the input like the value of x in radians and n where n is a number up to which we
want to print the sum of series.
Step3: For first term,
x=x*3.14159/180
t=x;
sum=x
Step4: For next term,
t = (t*(-1)*x*x)/(2*i*(2*i+1))
sum=sum + t;
#The formula for the ' sin x' is represented as
# sin x = x-x3/3!+x5/5!-x7/7!+x9/9!(where x is in radians)
Step5: Repeat the step4, looping 'n’ 'times to get the sum of first 'n' terms of the series.
Step6: Display the value of sum.
Step7: Stop the program.
Flowchart
Program:
x=float (input ("Enter the value for x:"))
a=x
n = int (input ("Enter the value for n:"))
x = x*3.14159/180
t=x;
sum=x
for i in range(1,n+1):
t=(t*(-1)*x*x)/(2*i*(2*i+1))
sum = sum + t;
print("The value of Sin(",a,")=",round(sum,2))
Output
Enter the value for x: 30
Result
Thus the sine series program has been executed and verified successfully.
Ex.No:1.d
Aim
To write a python program to find the weight of a motor bike.
Algorithm
Step1: Start the program
Step 2: Initialize values to the parts of the motorbike in weights (Chassis, Engine, Transmissions,
Wheels, Tyres, Body panels, Mudguards, Seat, Lights)
Step3: Process the following weight=weight + sum_motorbike[i]
Step 4: Repeat the step 3, looping 'n’' times to get the sum of weight of the
vehicleStep5: Display the Parts and Weights of the motorbike
Step 6: Display “Weight of the Motor bike”
Step7: Stop the program.
Flowchart
Program
sum_motorbike = {"Chassis":28,"Engine":22,"Transmissions":18,
"Wheels":30,"tyres":15,"Body_Panels" :120,"Mudguards" :6,"Seat":10,"lights":10}
weight = 0
for i in sum_motorbike:
weight = weight + sum_motorbike [i]
print("Parts and weights of the Motorbike")
for I in sum_motorbike.items():
print(i)
print("\n Weight of the Motor bike is:",weight)
Output
Result
Thus the weight of the motor bike program has been executed and verified successfully.
Ex.No:1.e
Aim
To write a python program to find the weight of a steel bar.
Algorithm
Weight of steel bar = (d2/162) * length (Where d-diameter value in mm and length value in
m) Step1: Start the program.
Step2: Read the values of the variable d and length.
Step4: Process the following weight = (d2/162kg/m)*length
Step5: Display the value of weight.
Step6: Stop the program.
Flowchart
Program
d =int (input("Enter the diameter of the steel bar in milli meter: " ))
weight =((d**2)/162)*length
print ("Weight of steel bar in kg per meter:",round(weight,2))
Output
Result
Thus the weight of the steel bar program has been executed and verified successfully.
Ex.No:1.f
Aim
To write a python program to compute the Electrical Current in Three Phase AC Circuit.
Algorithm
Step1: Start the program
Step2: Import math header file for finding the square root of 3
Step3: Read the values of pf, I and V.
Step4: Process the following:
Perform a three p has e power calculation using the following formula: P=√3* pf*I*V
Where pf-power factor, I-current , V-voltage and P–power
Step5: Display “The result is P”.
Step6: Stop the program.
Flowchart
Program
Import math
pf = float(input("Enter the Power factor pf (lagging): " ))
Output
Result
Thus the Electrical Current in Three Phase AC Circuit program has been executed and verified
successfully.
2. Python programming using
simple statements and
expressions
Aim
To write a python program to exchange the values of two variables.
Algorithm
Step1: Start the program
Step2: Read the values of two variables
Step 3: Print the values of the two variables before swapping.
#Tuple assignment
print("Swapping two values")
Output
Swapping two values
Result
Thus the exchange the values of two variables program has been executed and verified
successfully.
Ex.No:2.b
Aim
To write a python program to circulate the values of n variables
Algorithm
Step1: Start the program
Step2: Read the values of two variables
Step3: Display the values of the two variables before swapping
Step4: Process the following
Swapping of two variables using tuple assignment
operator. a,b = b,a
Step 5: Display the values of the two variables after swapping.
Step6: Stop the program.
Program
Print ("Circulate the values of n variables")
list1=[10,20,30,40,50]
print ("The given list is:",list1)
n = int (input("Enter how many circulations are
required:")) circular_list=list1[n:]+list1[:n]
print("After" , n, "circulation is:", circular_list)
Output
Output
deque ([1,2,3,4,5])
deque([4,5,1,2,3])
Result
Thus circulate the values of n variables program has been executed and verified successfully.
Ex.No:2.c
Aim
To write a python program to find the distance between two points
Algorithm
Step1: Start the program
Step2: Read the values of two points(x1,y1,x2,y2)
x1=int(input("EnterX1value:"))
y1=int(input("EnterY1 value:"))
x2=int(input("EnterX2value:"))
y2=int(input("EnterY2 value:"))
Result=math.sqrt(((x2-x1)**2)+((y2-y1)**2))
print("Distance between two points:",int(Result))
Output
Result
Thus the distance between two points program has been executed and verified successfully.
3. Scientific problems using Conditionals and
Iterative loops
Aim
To write a python program for the Number Series
Program
print ("Program for Number Series : Fibanacci
Sequence") n=int(input("How many terms?"))
f1=-1
f2=1
for i in range(n):
f3=f1+f2
print(f3,end=" ")
f1,f2=f2,f3
Output
sum=0
for i in range(1,n+1):
sum+=i**2
print ("The sum of series =",sum)
Output
Result
Thus the number series program has been executed and verified successfully.
Ex.No:3.b
Date: Number Patterns
Aim
To write a python program for the Number Patterns
a. Number Pattern_Type1
Algorithm
Step1: Start the program
Step2: Read the number of rows
Step 3: Process the following from i=1 to rows+1 times
Program
Print ("Program for Number Pattern")
for i in range(1,rows+1):
for j in range(0,i):
print(i, end="")
print ("")
Output
Program for Number Pattern
Enter the number of rows: 5
1
22
333
4444
55555
b. NumberPattern_Type2
c. Algorithm
Step1: Start the program
Step2: Read the number of rows
Step 3: Process the following from i=1 to rows+1 times
Step3a: Process the following from j=1toi+1times
Display j
Step4: Stop the program.
Program
c. Number Pattern
print("Program for Number
Pattern")rows=int(input("Enter the number of
rows: "))
for i in range(1,rows+1):
for j in range(1,i+1):
print(j,end="")
print("")
Output
Program for Number Pattern
Enter the number of rows: 5
1
12
123
1234
12345
Result
Thus the number patterns programs have been executed and verified successfully.
Ex.No:3.c
Date: Pyramid Patterns
Aim
To write a python program for the Pyramid Patterns
Algorithm
Step1: Start the program
Step2: Read the number of rows
Step3: Process the following from i=1 to rows+1times
Step3a: Process the following from space= 1to (rows-i)+1times
Display empty space
Step 3b: Process the following from j=0 to 2*i-1 times
Display ‘*’
Step4: Stop the program.
Program
Pyramid pattern
rows= int (input("Enter number of rows:"))
for i in range (1,rows+1):
for space in range (1,(rows-i)+1):
print(end=" ")
for j in range(0,2*i-1):
print("*",end="")
print()
Output
Result
Thus the pyramid pattern program has been executed and verified successfully.
4. Implementing
real-time/technical applications
using Lists, Tuples
Aim
To write a python program for items present in a library.
Algorithm
Program
print ("Welcome to Riya Advanced Library")
print(" ")Library=["Books", "e-Books", "Journals", "Audio
books", "Manuscripts", "Maps", "Prints", "Periodicals", "Newspapers"]
for i in Library:
print (i)
print("
"
) print(Library)
Library . Remove ("Prints")
print(Library)
Library.pop(4)print(Librar
y)Library.clear()print(Libr
ary)Library.append("CD’s
")print(Library)Library.ins
ert(0,"DVD's")print(Librar
y)
Print (Library. index ("DVD's"))
del Library[0:1]
print (Library)
Output
Welcome to Riya Advanced Library
Books
e-Books
Journals
Audio books
Manu scripts
Maps
Prints
Periodicals
Newspapers
['Books','e-
Books','Journals','Audiobooks','Manuscripts','Maps','Prints','Periodicals','Newspapers']
['Books','e- Books','Journals','Audiobooks','Manuscripts','Maps','Periodicals','Newspapers']
['Books','e- Books','Journals','Audiobooks','Maps','Periodicals','Newspapers']
[]['CD’
s']
["DVD's",
'CD’s']0
['CD’s']
Result
Thus the items present in a library program has been executed and verified successfully.
Ex.No:4.b
Date: Components of a car
Aim
To write a python program for components of a car.
Program
print("Components of a
car")print(" "
)
Main_parts=["Chassis","Engine","Auxiliaries"]Transmission_Syst
em=["Clutch","Gearbox", "Differential", "Axle"]
Body=["Steering system", "Braking system"]
print("Main Parts of the Car:", Main_parts)
print ("Transmission systems of the Car:",Transmission_System)
print("Body of the Car:",Body)
total_parts=[]total_parts.extend(Main_parts
)total_parts.extend(Transmission_System)to
tal_parts.extend(Body)
print(" ")
print("Total components of the car:",
len(total_parts)) print(" ")
total_parts. sort()
j=0
fori in total_parts:
j=j+1
print(j,i)
Output
Components of a car
Main Parts of the Car:['Chassis' , 'Engine', 'Auxiliaries']
Transmission systems of the Car: ['Clutch', 'Gearbox', 'Differential', 'Axle']
Body of the Car:['Steering system', 'Braking system']
91Auxiliaries
2 Axle
3 Braking system
4 Chassis
5 Clutch
6 Differential
7 Engine
8 Gearbox
9 Steering system
Result
Thus the components of a car program has been executed and verified successfully.
Ex.No:4.c Materials required for construction of a building
Date:
Aim
To write a python program for Materials required for construction of a building.
Program
print("Materials required for construction of a building")
print("Approximate
Price:\n1.Cement:16%\n2.Sand:12%\n3.Aggregates:8%\n4.Steelbars:24%\n5.Bricks:5%\n6.P
aints:4%\n7.Tiles:8%\n8.Plumbing items:5%\n9.Electricalitems:5%\n10.Wooden products:10%\
n11.Bathroom accessories:3%")materials=("Cement/Bag","Sand/Cubicfeet","Aggregates/
Cubicfeet","Steelba
rs/Kilogram","Bricks/Piece","Paints/Litres","Tiles/Squrefeet","Plumbingitems/meterorpiece","
Electrical items/meterorpiece","Woodenproducts/squarefeet","Bathroomaccessories/piece")
price=[410,50,25,57,7,375,55,500,500,1000,1000]
for i in range( len (materials)):
print(materials[i],":",price[i])
print("
"
) #materials[0]="Glass items" -tuple is
immutable price[0]=500
for i in range(len(materials)):
print(materials[i],":",price[i])
print("
"
) print("Operations of tuple / list")
print(min(price))
print(max(price))
print(len(price))
print(sum(price))
print(sorted(price))
print(all(price))
print(any(price))
Output
Materials required for construction of a building Approximate Price:
1.Cement:16%
2.Sand:12%
3.Aggregates:8%
4.Steel bars:24%
5.Bricks:5%
6.Paints:4%
7.Tiles:8%
8.Plumbing items:5%
9.Electricalitems:5%
10.Wooden products:10%
11.Bathroomaccessories:3%
Cement/Bag:4
10Sand/Cubicfeet:50Aggreg
ates/Cubicfeet:25Steel
bars/Kilogram :
57Bricks/Piece :7
Paints/Litres :
375Tiles/Squrefeet:
55
Plumbing items/meter or piece :
500Electrical items/meter or piece
: 500Wooden products/square
feet :
1000Bathroomaccessories/piece:10
00
Cement/Bag:500Sand/Cub
icfeet:50Aggregates/Cubic
feet : 25Steel
bars/Kilogram :
57Bricks/Piece :7
Paints / Litres :
375Tiles/Squrefeet:
55
Plumbing items/meter or piece :
500Electrical items/meter or piece :
500Wooden products/square feet :
1000Bathroomaccessories/piece:10
00
Operations of tuple / list 7
1000
11
4069
[7,25,50,55,57,375,500,500,500,1000,1000]
True
True
Result
Thus the Materials required for construction of a building program has been executed and verified
successfully.
5.Implementing real-time/technical
applications using Sets, Dictionaries.
Aim
To write a python program for language.
Program
LANGUAGE1 = {'Pitch', 'Syllabus', 'Script', 'Grammar',
'Sentences'};LANGUAGE2={'Grammar','Syllabus','Context','Words','Ph
onetics'};#setunion
print("UnionofLANGUAGE1and LANGUAGE2is",LANGUAGE1|LANGUAGE2)
#setinter section
print("IntersectionofLANGUAGE1andLANGUAGE2is ",LANGUAGE1
&LANGUAGE2)
#set difference
print("Difference of LANGUAGE1 and LANGUAGE2 is ",LANGUAGE1 -
LANGUAGE2)print("Difference of LANGUAGE1 and LANGUAGE2 is ",LANGUAGE2 -
LANGUAGE1) #set symmetric difference
print("Symmetric difference ofLANGUAGE1 andLANGUAGE2is ",LANGUAGE1
^LANGUAGE2)
Output
UnionofLANGUAGE1andLANGUAGE2is
{'Pitch','Syllabus','Phonetics','Script','Words','
Grammar','Sentences','Context'}
IntersectionofLANGUAGE1andLANGUAGE2is {'Syllabus',
'Grammar'} DifferenceofLANGUAGE1andLANGUAGE2is
{'Pitch','Sentences','Script'}Differe
nceofLANGUAGE1andLANGUAGE2is
{'Context','Words','Phonetics'}Sym
metricdifferenceofLANGUAGE1andLANGUAGE2is {'Pitch', 'Script', 'Words',
'Phonetics' , 'Sentences', 'Context'}
Result
Thus the language program has been executed and verified successfully.
Ex.No:5.b
Date: Components of an auto mobile
Aim
To write a python program for Components of an automobile.
Program
print("Components of an auto mobile")
print("\n")
print("Dictionary
keys")print(" "
) components={"Engine
parts":["piston","cylinderhead","oilpan","enginevalves","combustionchamber","gasket"],"Drive
transmission and steering parts":["Adjusting nut", "pit man arm shaft", "roller bearing", "steering gear
shaft"], "Suspensionandbrakeparts":["Breakpedal","Brakelines","Rotors/drums","Breakpads","Wheel
cylinders"],"Electricalparts":["Battery","Starter","Alternator","Cables"],"Body and chassis":["Roof
panel", "front panel"," screen pillar", "Lights", "Tyres"]}
for i in components.keys():
print(i)
print("\n")
print("Dictionary values")
print("")
for i in components. values():
print(i)
print("\n")print("Diction
ary items")
print("
"
) for i in components.items():
print(i)
print("\n")
accessories={"Bumper":["front","back"]}
components.update(accessories)compone
nts['Bumper']=["front and
back"]print("Dictionary items")
print("
"
) for i in components.items():
print(i)
print("\n")
print(len(components))
del components["Bumper"]
components .pop("Electrical parts")
components. pop item()
print("\n")print("Diction
ary items")
print("
"
) for i in components.items():
print(i)
components.clear();
print(components)
Output
Components of an automobile
Dictionary keys
Engine parts
Drive transmission and steering
parts Suspension and brake parts
Electrical parts
Bodyand chassis
Dictionary values
['piston', 'cylinder head','oilpan','enginevalves','combustionchamber','gasket']['Adjusting
nut', 'pit manarm shaft', 'roller bearing', 'steering gear shaft']
['Breakpedal','Brakelines','Rotors/drums','Breakpads','Wheelcylinders']['Batter
y','Starter','Alternator','Cables']
['Roofpanel', 'frontpanel', 'screenpillar', 'Lights', 'Tyres']
Dictionary items
('Engineparts',['piston','cylinderhead','oilpan','enginevalves','combustionchamber','gasket'])('Drive
transmission and steering parts', ['Adjusting nut', 'pitman arm shaft', 'roller bearing', 'steering gear
shaft'])
('Suspension and brake parts', ['Break pedal', 'Brake lines', 'Rotors/drums', 'Break pads',
'Wheel cylinders'])
('Electrical parts', ['Battery', 'Starter', 'Alternator', 'Cables']) ('Bodyandchassis',
['Roofpanel','frontpanel','screenpillar','Lights','Tyres'])
Dictionary items
('Engineparts',['piston','cylinderhead','oilpan','enginevalves','combustionchamber','gasket'])('Drive
transmission and steering parts', ['Adjusting nut', 'pitman arm shaft', 'roller bearing', 'steering
gear
shaft'])
('Suspension and brake parts', ['Break pedal', 'Brake lines', 'Rotors/drums', 'Break pads',
'Wheel cylinders'])
('Electrical parts',['Battery', 'Starter', 'Alternator', 'Cables'])
('Body and chassis', ['Roof panel', 'front panel', 'screen pillar', 'Lights', 'Tyres']) ('Bumper',
['front and back'])
Dictionary items
('Engineparts',['piston','cylinderhead','oilpan','enginevalves','combustionchamber','gasket'])('Drive
transmission and steering parts', ['Adjusting nut', 'pitman arm shaft', 'roller bearing', 'steering
gear shaft'])
('Suspension and brake parts', ['Break pedal', 'Brake lines', 'Rotors/drums', 'Break pads',
'Wheel cylinders'])
{}
Result
Thus the components of an automobile program has been executed and verified successfully.
Ex.No:5.c
Date: Elements of a civil structure
Aim
To write a python program for Elements of a civil structure.
Program
print("Elements of a civil structure")
print(" ")
print("1.foundation\n2.floors\n3.walls\n4.beamsandslabs\n5.columns\n6.roof
\n7.stairs\n8.parapet\n9.lintels\n10.Dampproof")elements1={"
foundation","floors","floors","walls","beamsandslabs","colum
ns","roof","stairs","parapet","lintels"}print("\n")
print(elements1)
print("\n")
elements1.add("dampproof")#add
print(elements1)elements2={"plant
s","compound"}print("\n")
print(elements2)
print("\n")
elements1. update(elements2)
#extending print(elements1)
elements1. remove("stairs") #data removed, if item not present raiseerror
print(elements1)
elements1. discard("hardfloor")#dataremoved,ifitemnotpresentnotraiseerrorprint(elements1)
elements1.pop()
print(elements1)
print(sorted(elements1)) print("\
n")
print("set operations")
s1={"foundation", "floors"}
s2={"floors", "walls", "beams"}
print(s1.symmetric_difference(s2))
print(s1.difference(s2))
print(s2.difference(s1))
print(s1.intersection(s2))
print(s1.union(s2))
Output
Elements of a civil structure
1.foundation
2.floors
3.walls
4.beamsandslabs
5.columns
6.roof
7. stairs
8. Parapet
9.lintels
10.Dampproof
{'stairs','floors','roof','walls','columns','lintels','foundation','beamsandslabs','parapet'}
{'stairs', 'floors', 'roof', 'walls', 'columns', 'lintels', 'foundation', damp proof', 'beams and slabs',
'parapet'}
{'compound', 'plants'}
{'stairs','floors','roof','plants','walls','columns','compound','lintels','foundation','dampproof','beams and
slabs', 'parapet'}
{'floors', 'roof', 'plants', 'walls',
'columns','compound','lintels','foundation','dampproof','beamsandslabs','parapet'}
{'floors','roof','plants','walls','columns','compound','lintels','foundation','dampproof','beamsandsla
bs','parapet'}
{'roof','plants','walls','columns','compound','lintels','foundation','damp proof', 'beams and
slabs', 'parapet'}
['beamsandslabs','columns','compound','dampproof','foundation','lintels','parapet','plants','roof','
walls']
set operations
{'foundation', 'beams', 'walls'}
{'foundation'}
{'beams', 'walls'}
{'floors'}
{'floors', 'beams', 'foundation', 'walls'}
Result
Thus the elements of a civil structure program has been executed and verified successfully.
6. Implementing programs using Functions.
(Factorial, largest number in a list, area of
shape)
Ex.No:6.a Factorial
Date:
Aim
To write a python program for factorial.
Program
def factorial(num): #function definition
fact=1
for i in
range(1,num+1):
fact=fact*i
return fact
number=int(input("Please enter any number to find the
factorial:"))result=factorial(number) #function calling
print("Using functions- The factorial of %d=%d"%(number, result))
Output
Please enter any number to find the
factorial:6 Usingfunctions-
Thefactorialof6=720
Result
Thus the factorial program has been executed and verified successfully.
Ex.No:6.b
Date: Largest number in alist
Aim
To write a python program for Largest number in a list.
Program
Def myMax (list1):
maxi = list1[0]
for x in list1:
if(x>maxi):
maxi= x
return maxi
list1=[100,200,500,150,199,487]
print("Largest element in the listis: ",myMax(list1))
def myax(list1):
maxi = list1[0]
for x in list1:
if(x>maxi):
maxi=x
return maxi
list1=[100,200,500,150,199,487]
print("Largest element in the listis:",myMax(list1))
Output
Largest element in the listis:500
Result
Thus the largest number in a list program has been executed and verified successfully.
Ex.No:6.c
Date: Area of shape
Aim
To write a python program for area of a shape.
Program
def calculate_area(name):
name=name.lower()
if name=="rectangle":
l=int(input("Enter rectangle's length:"))
b=int(input("Enter rectangle's breadth:"))
#calculate area of
rectangle rect_area=l*b
print("The area of rectangle is{rect_area}.")
elif name=="square":
s=int(input("Enter square's sidel ength:"))
elif name=="triangle":
h = int(input("Enter triangle's height length: "))
b= int(input("Enter triangle's breadth length:"))
elif name=="circle":
r=int(input("Enter circle's radius length:"))
pi=3.14
elifname=='parallelogram':
b=int(input("Enter parallelogram's base length:"))h=
int(input("Enter parallelogram's height length:"))
#calculate area of
parallelogram para_area =b*h
print(f"The area of parallelogram is{para_area}.")
else:
print("Sorry! This shape is not available") print("CalculateShapeArea:\nRectangle\nSquare\nTriangle\
nCircle\nParallelogram") shape_name=input("Enter the name of shape whose area you want to find: ")
calculate_area(shape_name)
Output
Calculate Shape Area:
Rectangle
Square
Triangle
Circle
Parallelogram
Enter The Name Of Shape Whose area you want to find:
Triangle Enter triangle' s height length:10
Enter triangle's breadth length:5
The area of triangle is 25.0.
Result
Thus the area of a shape program has been executed and verified successfully.
7. Implementing programs using Strings.
(reverse, palindrome, character count, replacing
characters)
Ex.No:7.a
Date: String Reverse
Aim
To write a python program for string reverse.
Program
def rev(string):string="".join(reversed(string))
return string
Output
Enter any string: Riya
The Original String is: Riya
The reversed string (using reversed function)is: akinra V
Result
Thus the String reverse program has been executed and verified successfully.
Ex.No:7.b
Date: Palindrome
Aim
To write a python program for palindrome.
Program
string=input("Enterthestring:")
string=string.casefold()
print(string)
rev_string=reversed(string)
if(list(string)==list(rev_string)):
print(f"Givenstring{string}isPalindrome.")
else:
print(f"Givenstring{string}isnotPalindrome.")
Output
Enter the string: Amma
amma
Given string amma is Palindrome.
Result
Thus the palindrome program has been executed and verified successfully.
Ex.No:7.c
Date: Character Count
Aim
To write a python program for character count.
Program
string=input("Enter the string:")
print("Total characters in the given string is",len(string))
char=input("Enter a character to count:")
val=string.count(char)
print(val,"\n")
Output
Enter the string: Mega riya
Total characters in the given string
is 11Enteracharactertocount:a
3
Result
Thus the character count program has been executed and verified successfully.
Ex.No:7.d
Date: Replacing characters
Aim
To write a python program for replacing character.
Program
string=input("Enter the string:")
str1=input("Enter old string:")
str2=input("Enterreplacablestring:")
print(string.replace(str1,str2))
Output
Enter the string: Problem Solving and
Python Programming Enter oldstring: Python
Enter replacable string: Java
Problem Solving and Java Programming
Result
Thus the replacing character program has been executed and verified successfully.
8. Implementing programs using written
modules and Python Standard Libraries
(numpy, pandas, Matplotlib, scipy)
Ex.No:8.a
Date: Numpy
Aim
To write a python program for numpy.
Program
#1D array
import numpy as np
arr=np.array([10,20,30,40,50])
print("1Darray:\n",arr)
print(" ")
#2D array (matrix)
Import numpy as np
arr=np.array([[1,2,3],[4,5,6]])
print("\n2 D array:\n",arr)
print("\n2ndelementon1strowis:", arr[0,1])
print(" ")
#3Darray (matrices)
import numpy as np
arr=np.array([[[1,2,3],[4,5,6]],[[1,2,3],[4,5,6]]])
print("\n3Darray:\n", arr) print("\
n3rdelementon2ndrowofthe1stmatrixis",arr[0,1,2])
Output
1 Darray:
[1020304050]
2 Darray:
[[123]
[4 56]]
2ndelementon1st rowis:2
3 Darray:
[[[12 3]
[456]]
[[12 3]
[456]]]
3rdelementon2ndrowofthe1stmatrixis 6
Result
Thus the numpy program has been executed and verified successfully.
Ex.No:8.b
Date: Pandas
Aim
To write a python program for pandas.
Program
Output
0 a
1 b
2 c
3 d
4 e
dtype:object
{'cars':['BMW','Volvo','Ford'],'passings':[3,7,2]}
cars passings
0 BMW 3
1 Volvo 7
2 Ford 2
Result
Thus the pandas program has been executed and verified successfully.
Ex.No:8.c
Date: Scipy
Aim
To write a python program for scipy.
1.Program
from scipy import
constantsprint(constants.mi
nute)print(constants.hour)pr
int(constants.day)print(cons
tants.week)print(constants.y
ear)print(constants.Julian_y
ear)
print(constants.kilo)#printingthekilometerunit(inmeters)print(constants.gram)#p
rintingthegramunit(inkilograms)print(constants.mph)#printingthe miles-per-
hour unit (in meters per seconds)
print(constants.inch)
1. Output
60.0
3600.0
86400.0
604800.0
31536000.0
31557600.0
1000.0
0.001
0.44703999999999994
0.0254
2. Program
Import numpy as np
From scipy import io as
sio array=np.ones((4,4))
sio.savemat('example.mat',{'ar':array})
data=sio.loadmat("example.mat", struct_as_record=True)
data['ar']
2.Output
array([[1.,1.,1.,1.],
[1.,1.,1.,1.],
[1.,1.,1.,1.],
[1.,1., 1.,1.]])
Result
Thus the scipy program has been executed and verified successfully.
Ex.No:8.4
Date: Matplotlib
Aim
To write a python program for matplotlib.
1.Program
Import matplotlib.py plot as
plt import numpy as np
plt.plot([-1,-4.5,16,23])
plt.show()
plt.plot([10,200,10,200,10,200,10,200])
plt.show()
xpoints=np.array([0,6])
ypoints=np.array([0,250])
plt.plot(xpoints,ypoints)
plt.show()
1. Output
2. Program
From scipy import misc
From matplotlib import py plot as plt
import numpy as np
#get face image of panda from misc package
panda=misc.face()
#plotor show image of face
plt.imshow(panda )
plt.show()
2. Output
Result
Thus the matplotlib program has been executed and verified successfully.
9. Implementing
real-time/technical applications
using File handling.
(copy from one file to another, word count, longest word)
Ex.No:9.a
Aim
To write a python program for Copy from one file to another.
Program
Output
Source File Name:
mega.txt Hello India
Result
Thus the Copy from one file to another program has been executed and verified successfully.
Ex.No:9.2
Date: Wordcount
Aim
To write a python program for word count.
Program
file=open("mega.txt","r")data=f
ile.read()words=data.split()
print("Number of words in text file:", len(words))
Output
Source File Name : mega.txt
Hello India
Number ofwordsintextfile:2
Result
Thus the word count program has been executed and verified successfully.
Ex.No:9.c
Date: Longest word
Aim
To write a python program for longest word.
Program
Def longest_word(filename):
with open(filename,"r") as infile:
words=infile.read().split()
max_len=len(max(words,key=len))
return[wordforwordinwordsiflen(word)==max_len]file_
name=input("Enter the file
name:")print(longest_word(file_name))
Output
SourceFileName:mega.txt
Welcome toIndia
Enterthefilename:mega.txt['
Welcome']
Result
Thus the longest word program has been executed and verified successfully.
10. Implementing
real-time/technical applications using
Exception handling
Aim
To write a python program for divide by zero error.
Program
a=int(input("Enter the value of a:"))
b=int(input("Enter the value of b:"))
try:
c=a/b
print("Divide a / b:",c)
except Zero Division Error:
print("Found Divide by Zero Error!")
Output
Enter the value of a: 50
Enter the valueofb:0
Found Divide by Zero Error!
Result
Thus the divide by zero error program has been executed and verified successfully.
Ex.No:10.b
Date: Voter’s age validity
Aim
To write a python program for voter’s age validity.
Program
try:
age=int(input("Enter your age:"))
if age>18:
print("Eligible to vote")
else:
print("Not eligible to vote")
except Value Error as err:
print(err)
finally:
print("Thank you")
Output
Enter your
age:21 Eligible
to vote Thank
you
Enteryourage:17
Not eligible to vote
Thank you
Result
Thus the voter’s age validity program has been executed and verified successfully
Ex.No:10.3
Date: Student mark range validation
Aim
To write a python program for student mark range validation.
Program
try:
python=int(input("Enter marks of the Python subject:
")) print("Python Subject Grade", end=" ")
if(python>=90):
print("Grade: O")
elif(python>=80andpython<90):
print("Grade:A+")
elif(python>=70andpython<80):
print("Grade:A")
elif(python>=60andpython<70):
print("Grade:B+")
elif(python>=50andpython<60):
print("Grade:B")
else:
print("Grade: U")
except:
print("Entered data is wrong, Try Again")
finally:
print("Thank you")
Output
Enter marks of the Python subject: 95
Python Subject Grade Grade : O
Thank you
Result
Thus the student mark range validation program has been executed and verified successfully.
11. Exploring Pygame tool.
Ex.No:11 Exploring pygame
Date:
Aim
To write a python program for exploring pygame.
Program
100% |4.0 MB
171kB/s
Installing collected packages: pygame
Successfully installed pygame-1.9.3
7. Now, pygame installed successfully
8. To see if it works, run one of the included examples in pygame-1.9.3
Open command prompt
Type the following
Result
Thus the exploring pygame program has been executed and verified successfully.
12.Developing a game activity using Pygame like
bouncing ball, car race etc.
Ex.No:12
Date: Simulate bouncing ball using pygame
Aim
To write a python program for simulate bouncing ball using pygame.
Program:
import pygame
pygame.init()
window_w=800
window_h=600
white=(255,255,255)
black=(0,0,0)
FPS=120
window =pygame.display.set_mode((window_w,window_h))
clock=pygame.time.Clock()
defgame_loop():
block_size=20
velocity=[1,1]
pos_x=window_w/2
pos_y=window_h/2
running=True
while running:
for event in pygame.event.get():
ifevent.type==pygame.QUIT:
pygame.quit()
quit()
pos_x+=velocity[0]
pos_y+=velocity[1]
ifpos_x+block_size>window_w or pos_x< 0:
velocity[0]=-velocity[0]
ifpos_y+block_size>window_h or pos_y< 0:
velocity[1]=-velocity[1]
window.fill(white)
pygame.draw.rect(window, black, [pos_x, pos_y, block_size, lock_size])
pygame.display.update()
clock.tick(FPS)
game_loop()
Output:
Result
Thus the simulate bouncing ball using pygame program has been executed and verified successfully.
Ex.No:13
Date: Implementing a program using File Handling
Aim:
To write a python program using File Handling.
Program
# Python code to create a file
file = open('geek.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()
O u tp u t:
Happy New
Year….
Welcome
Result
Thus the python program using File Handling has been executed and verified successfully.
Ex.No:14 Implementing program using written modules and Python Standard
Libraries Date:
Aim:
To write a Python program using written modules and Python Standard Libraries.
Program:
A = 16
B = 3.14
print(sqrt(A))
print(sin(B))
Output:
4.0
0.0015926529164868282
Result
Thus the python program using written modules and Python Standard Libraries has been executed and verified
successfully.