Ge3171-Python Lab

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 82

GE3171 PROBLEM SOLVING AND

PYTHON PROGRAMMING LABORATORY


MANUAL

REGULATION 2021
GE3171 PROBLEM SOLVING AND
PYTHON PROGRAMMING LABORATORY
MANUAL REGULATION 2021
GE3171 PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY LTP C 0042

COURSEOBJECTIVES:

 To understand the problem solving approaches.


 To learn the basic programming constructs in Python.
 To practice various computing strategies for Python-based solutions to real world
problems.
 To use Python data structures-lists, tuples, dictionaries.
 To do input/output with files in Python.
LISTOF EXERCISES:
1. Identification and solving of simple real life or scientific or technical problems, and developing
flow charts for the same. (Electricity Billing, Retail shop billing, Sin series, weight of a motor
bike, Weight of a steel bar, compute Electrical Current in Three Phase AC Circuit, etc.)
2. Python programming using simple statements and expressions (exchange the values of two
variables, circulate the values of n variables, distance between two points).
3. Scientific problems using Conditionals and Iterative loops .(Number series, Number Patterns,
pyramid pattern)
4. Implementing real-time/technical applications using Lists, Tuples. (Items present in a
library/Components of a car/ Materials required for construction of a building –operations of list
& tuples)
5. Implementing real-time/technical applications using Sets, Dictionaries.(Language, components of
an automobile, Elements of a civil structure, etc.- operations of Sets &Dictionaries)
6. Implementing programs using Functions.(Factorial, largest number in a list, area of shape)
7. Implementing programs using Strings. (reverse, palindrome, character count, replacing
characters)
8. Implementing programs using written modules and Python Standard Libraries (pandas, numpy,
Matplotlib, scipy)
9. Implementing real-time/technical applications using File handling.(copy from one file to another,
word count, longest word)
10. Implementing real-time/technical applications using Exception handling. (divide by zero error,
voter’s age validity, student mark range validation)
11. Exploring Pygame tool.
12. Developing a game activity using Pygame like bouncing ball, car race etc.

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

1b Retail Shop Billing

1c Sin Series

1d Weight of a Motorbike

1e Weight of a Steel Bar

1f Compute Current in Three Phase AC Circuit

2a Exchange the values of two variables

2b Circulate the values of N variables

2c Distance between two points

3a Number Series

3b Number Patterns

3c Pyramid Pattern

4a Items present in a library - operations of list & tuples

4b Components of a Car - operations of list & tuples

4c Materials required for construction of a building - operations of list & tuples

5a Language – operations of Sets & Dictionaries

5b Components of an automobile – operations of Sets & Dictionaries


5c Elements of a civil structure, etc. – operations of Sets & Dictionaries

6a Factorial

6b Largest number in a list

6c Area of shape

7a Reverse

7b Palindrome

7c Character count

7d Replacing characters
8a Numpy

8b Pandas

8c Matplotlib

8d Scipy

9a Copy one file to another using File handling

9b Word Count using File handling

9c Longest Word using File handling

10a Divide by zero error using Exception handling

10b Voter’s age validity using Exception handling

10c Student mark range validation using Exception handling

11 Exploring pygame

12 Simulate bouncing ball using pygame

13 Implementing a python program using File Handling

14 Implementing a python program using written Modules and Standard Library


Functions.
1. Identification and solving of simple real life or
scientific or technical problems, and developing
Flowcharts for the same.

(Electricity Billing, Retail shop billing, Sin series,


weight of a motor bike, Weight of a steel bar,
compute Electrical Current in Three Phase AC
Circuit)
Ex.No:1.a Electricity Billing
Date :

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

please enter the number of units you consumed

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

Step 5: Repeat the step4 until the condition get fails.

Step6: Display the value of “amount”.


Step7: Stop the program.
Flowchart
Program
print("Welcome to Riya Retail Shopping")
print("List of items in our market")
soap=60;powder=120;tooth_brush=40;paste=80;perfume=250
amount=0
print("1.Soap\n2.Powder\n3.Tooth Brush\n4.Tooth Paste\
n5.Perfume")print("ToStoptheshoppingtypenumber0")
while(1):
item = int (input("Enter the item
number:")) if(item==0):
break
else:
if(item<=5):
quantity = int (input("Enter the quantity:"))

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

print("Total amount need to pay is:", amount)

print("Happy for your visit")


Output

Welcome to Riya Retail Shopping

List of items in our market


1. Soap

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

Enter the value for n: 5


The value of Sin (30.0) = 0.5

Result
Thus the sine series program has been executed and verified successfully.
Ex.No:1.d

Date: Weight of a Motor bike

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

Parts and weights of the Motorbike


('Chassis',28)
('Engine',22)
('Transmissions',18)
('Wheels', 30)
('tyres', 15)
('Body_Panels',120)
('Mudguards', 6)
('Seat',10)
('lights', 10)
Weight of a Motor bike is : 259

Result
Thus the weight of the motor bike program has been executed and verified successfully.
Ex.No:1.e

Date: Weight of a steelbar

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

length=int (input("Enter the length of the steel bar in meter: " ))

weight =((d**2)/162)*length
print ("Weight of steel bar in kg per meter:",round(weight,2))

Output

Enter the diameter of the steel bar in millimeter : 6


Enter the length of the steel bar in meter : 3
Weight of steel bar in kg per meter :0.67

Result
Thus the weight of the steel bar program has been executed and verified successfully.
Ex.No:1.f

Date: Compute Electrical Current in Three Phase AC Circuit

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

I=float (input ("Enter the Current I: " ))

V = float (input ("Enter the Voltage V:"))


P = math.sqrt (3)*pf*I*V
print("Electrical Current in Three Phase AC Circuit:",round(P,3))

Output

Enter the Power factor pf (lagging): 0.8


EntertheCurrentI:1.7
Enter the Voltage V : 400
Electrical Current in Three Phase AC Circuit : 942.236

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

(Exchange the values of two variables, circulate the


values of n variables, distance between two
points).
Ex.No:2.a

Date: Exchange the values of two variables

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.

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
#with temporary variable
print("Swapping two values")

a=int (input("Enter the value of A:"))


b=int(input("Enter the value of B:"))
print("Before Swapping\n A value is:", a, "B valueis:",b)
c=a #with temporary variable
a=b
b=c
print("After Swapping \n A value is:",a,"B value is:",b)

# without temporary variable


print("Swapping two values")
a=int (input("Enter the value of A:"))
b=int (input("Enter the value of B:"))
print ("Before Swapping\n A value is:",a, "B value
is:",b) a = a+b #without temporary variable
b=a-b
a=a-b
print ("After Swapping\n A value is:",a," B value is:",b)

#Tuple assignment
print("Swapping two values")

a=int (input("Enter the value of A:"))

b=int (input("Enter the value of B:"))


print ("Before Swapping\n A value is:",a," B value is:",b)
a, b = b, a # Tuple assignment
print ("After Swapping \n A value is:",a, "B value is:",b)

Output
Swapping two values

Enter the value of A: 65

Enter the value of B : 66


Before Swapping
A value is: 65 B value is : 66
After Swapping
A value is: 66 B value is: 65

Result
Thus the exchange the values of two variables program has been executed and verified
successfully.
Ex.No:2.b

Date: Circulate the values of n variables

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

Circulate the values of n variables


The given list is : [10,20,30,40,50]
Enter how many circulations are required :3
After %f circulation is :[40,50,10,20,30]
Program
from collections import deque
lst =[1,2,3,4,5]
d= deque (lst)
print d
d.rotate(2)
print d

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

Date: Distance between two points

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)

Step3: Process the following


Result = math.sqrt (((x2-x1)**2)+((y2-y1)**2))
Step4: Display the result of distance between two points.
Step5: Stop the program.
Program
Import math
print ("Enter the values to find the distance between two
points")

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

Enter the values to find the distance between two points


EnterX1value:2
Enter Y1 value: 4
Enter X2 value: 4
EnterY2 value:8
Distance between two points:4

Result
Thus the distance between two points program has been executed and verified successfully.
3. Scientific problems using Conditionals and
Iterative loops

(Number series, Number Patterns, pyramid pattern)


Ex.No:3.a Number Series
Date:

Aim
To write a python program for the Number Series

a. Fibonacci sequence: 0 1 1 2 3 5 81321 34


Algorithm
Step1: Start the program
Step2: Read the number of terms
nStep3:Initializef1 =-1,f2=1
Step4: Process the following from i=0 to n times
f3=f1+f2
Display f3
Do the tuple assignment f1,f2=f2,f3
Step5: Stop the program.

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

Program for Number Series : Fibonacci


Sequence How manyterms?10
Fibonacci is sequence : 0 1 1 2 3 5 8 13 21 34
b. Number Series: 12+22+…+n2
Algorithm
Step1: Start the program
Step2: Read the number of terms n
Step3: Initialize sum=0
Step 4: Process the following from i=1 to n+1 times
Sum = sum + i**2

Step5: Display sum


Step6: Stop the program.
Program
print ("Program for Number Series")
n=int(input("How many terms? "))

sum=0
for i in range(1,n+1):
sum+=i**2
print ("The sum of series =",sum)

Output

Program for Number Series:


How many terms? 5
The sum of series = 55

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

Step3 a: Process the following from j = 0 to I times


Display
iStep4: Stop the program.

Program
Print ("Program for Number Pattern")

rows= int (input("Enter the number of rows: "))

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

Program for Pyramid Pattern

Enter the number of rows: 4


*
***
*****
* * * * ** *

Result
Thus the pyramid pattern program has been executed and verified successfully.
4. Implementing
real-time/technical applications
using Lists, Tuples

(Items present in a library/Components of a


car/Materials required for construction of
a building –operations of list & tuples)
Ex.No:4.a
Date: Items present in a library

Aim
To write a python program for items present in a library.

Algorithm

Step1: Start the program


Step2: Initialize the Library list with the following items "Books","e-
Books”,"Journals","Audiobooks","Manuscripts","Maps","Prints","Peri
odicals","Newspapers"
Step3: Process the following from I in Library
Display i
Step 4: Remove an item “Prints” from
Library listStep5: Display all items from
Library list Step 6: Remove 4th index item
from Library listStep7: Display all items from
Library list Step 8: Delete all items from
Library listStep9: Display the Library list
Step10: Add an item "CD’s" to the Library list
Step 11: Insert an item "DVD's" at index 0 to the Library
listStep12: Display the Library list
Step13: Display an index of "DVD's" from the Library list
Step 14: Using slice operator deletes an item at index 0 from the Library
listStep12: Display the Library list
Step13: Stop the program

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

Total components of the car:

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.

(Language, Components of an automobile, Elements of


acivil structure, etc.-operations of Sets & Dictionaries)
Ex.No:5.a
Date: Language

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

#calculate area of square


sqt_area=s *s
print(f"The area of square is{sqt_area}.")

elif name=="triangle":
h = int(input("Enter triangle's height length: "))
b= int(input("Enter triangle's breadth length:"))

#calculate area of triangle


tri_area =0.5*b*h
print(f "The area of triangle is{tri_area}.")

elif name=="circle":
r=int(input("Enter circle's radius length:"))
pi=3.14

#calculate area of circle


circ_area =pi*r*r
print("The area of circle is{circ_area}.")

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

s=input("Enter any string:")


print("The Original Stringis:",
end="") print(s)
print("Thereversedstring(usingreversedfunction)is:",end="")pri
nt(rev(s))

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

Import pandas mydata=['a','b','c','d','e']


myvar=pandas.Series(mydata)
print(myvar)
print("\n")
mydataset={'cars':["BMW","Volvo","Ford"],'passings':[3,7,2]}
print(mydataset)
myvar=pandas.DataFrame(mydataset)
print(myvar)

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

Date: Copy from one file to another

Aim
To write a python program for Copy from one file to another.

Program

from sh util import copy file


sourcefile =input("Enter source filename: ")
destinationfile=input("Enter destination filename:")
copyfile(sourcefile, destinationfile)
print("File copied successfully!")
c = open(destinationfile, "r")
print(c.read())
c.close()

Output
Source File Name:
mega.txt Hello India

Enter source file name: mega.txt


Enter destination filename:riya.txt
File copied successfully!
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

(divide by zero error, voter’s age validity, student


mark range validation)
Ex.No:10.a
Date: Divide by zero error

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

Enter your age: riya


Invalid literal for int() with base10:
'riya' 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

Enter marks of the Python subject t: a


Entered data is wrong,
Try Again
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

To install Pygame Module


Steps
1. Install python 3.6.2 into C:\
2. Go to this link to install pygamewww.pygame.org/download.shtml
3. Click
Pygame-1.9.3.tar.gz ~ 2M and download zar file
4. Extract the zar file into C:\Python36-32\Scripts folder
5. Open command prompt
6. Type the following command
C:\>py –m pip install pygame –user
Collecting pygame
Downloading pygame-1.9.3-cp36-cp36m-win32.whl (4.0MB)

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

C:\>cd Python36-32\Scripts\pygame-1.9.3 C:\


Python36-32\Scripts\pygame-1.9.3>cd examples
C:\Python36-32\Scripts\pygame-1.9.3\examples>aliens.py
C:\Python36-32\Scripts\pygame-1.9.3\examples>

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:

Ball is bouncing on Display Screen

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

# Python code to illustrate read() mode


file = open("file.txt", "r")
print (file.read())

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:

# Importing specific items


from math import sqrt, sin

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.

You might also like