You are on page 1of 79

C ABDUL HAKEEM COLLEGE OF ENGINEERING &TECHNOLOGY

(Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai)(NBA


Accredited & ISO 9001:2000 Certified Institution) Melvisharam – 632
509. Ranipet District, Tamilnadu.

Name ……………………………………………………………………………………….

Year…………………... Semester………………….. Branch…………………….....

Subject Code……................ Subject Name…………………..……………………………..……………

University Register Number :

Certificate

Certified that this is the bonafide record of work done by the above student in the
……………………………………………… Laboratory during the year 2023 – 2024.

Faculty In charge Head of the Department

Submitted for the University Practical Examination held on ………………………….

Examiners

Date: …………………………… Centre Code: …………………

Internal: ……………………….. External: ………………………

i
Index

Ex. Date Title Page Marks Staff


No. No. Signature

1a Electricity Billing 1

Retail Shop Billing


1b 4
Sin Series
1c 7

Weight of a Motor bike


1d 10

Weight of a steel bar


1e 13

Compute Electrical Current


in Three Phase AC Circuit
1f 15

Exchange the values of two


2a variables 17

Circulate the values of n variables


2b 20

Distance between two points


2c 22

Number Series
3a 24

Number Patterns
3b 26

Pyramid Patterns
3c 28

ii
Items present in a library
4a 30

Components of a Car
4b 32

Materials required for


4c construction of a building 34

Language
5a 36

Components of an automobile
5b 37

Elements of a civil structure


5c 40

Factorial
6a 43

Largest number in a list


6b 44

Area of shape
6c 45

Reverse
7a 47

Palindrome
7b 49

Character count
7c 50

Replacing characters
7d 51

Numpy
8a 52

iii
Pandas
8b 54

Matplotlib
8c 58

Scipy
8d 61

Copy one file to another using


9a File handling 63

Word Count using File handling


9b 65

Longest Word using File handling


9c 66

Divide by zero error using


10a Exception handling 67

Voter’s age validity using


10b Exception handling 68

Student mark range validation


10c using Exception handling 69

Exploring pygame
11 71

Simulate bouncing ball using


12 pygame 73

iv
Ex.No:1.a
Electricity Billing
Date :

Aim

To write a python program for the Electricity Billing.

Procedure:
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

1
Flowchart

2
Program
Unit = int (input("Please enter Number of Unit you Consumed:"))
if (unit<=100):
usage = unit *5
elif(unit<=200):
usage = (100*5)+((unit-00)*7)
elif (unit<= 300):
usage = (100*5)+(100*7)+((unit-0)*10)
else:
usage = (100*5)+(100*7)+(100*10)+((unit-300)*15)
print ("Electricity Bill=",usage)
print ("Note: No additional charge will be calculated")

Output
Please enter Number of Unit you consumed: 650

Electricity Bill=7450.00
Note: No additional charge will be calculated

Result
Thus the Electricity Billing program has been executed and verified successfully.

3
Ex.No:1.b
Retail Shop Billing
Date:

Aim
To write a python program for the Retail Shop Billing.

Procedure:
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 st

ep4 until the condition get fails.

Step6: Display the value of “amount”.


Step7: Stop the program.
Flowchart

4
Program
print("Welcome to 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.ToothPaste\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")

5
OUTPUT

Welcome to Retail Shopping

List of items in our market

1.Soap

2.Powder

3.Tooth Brush

4.ToothPaste

5.Perfume

ToStoptheshoppingtypenumber0

Enter the item number:1

Enter the quantity:2

Enter the item number:0

Total amount need to pay is: 120

Happy for your visit

Result
Thus the Retail Shopping Billing program has been executed and verified successfully
6
Ex.No:1.c
Sin Series

Date :

Aim
To write a python program for sin series.

Procedure:
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.

7
Flowchart

8
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:4


Enter the value for n:2
The value of Sin( 4.0 )= 0.07

Result
Thus the sine series program has been executed and verified successfully.

9
Ex.No:1.d
Weight of a Motor bike
Date:

Aim
To write a python program to find the weight of a motor bike.

Procedure:
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.

10
Flowchart

11
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 the Motor bike is: 259

Result
Thus the weight of the motor bike program has been executed and verified successfully.

12
Ex.No:1.e
Weight of a steel bar
Date:

Aim
To write a python program to find the weight of a steel bar.

Procedure:
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

13
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 milli meter: 3


Enter the length of the steel bar in meter: 2
Weight of steel bar in kg per meter: 0.11

Result
Thus the weight of the steel bar program has been executed and verified successfully.

14
Ex.No:1.f
Compute Electrical Current in Three Phase AC Circuit
Date:

Aim
To write a python program to compute the Electrical Current in Three Phase AC Circuit.

Procedure:
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

15
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): 3


Enter the Current I: 4
Enter the Voltage V:5
Electrical Current in Three Phase AC Circuit: 103.923

Result
Thus the Electrical Current in Three Phase AC Circuit program has been executed and verified
successful

16
Ex.No:2.a

Exchange the values of two variables


Date:

Aim
To write a python program to exchange the values of two variables.

Procedure:
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 value is:",b)
c=a #with temporary variable
a=b
b=c
print("After Swapping \n A value is:",a,"B value is:",b)

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

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

19
Ex.No:2.b
Circulate the values of n variables
Date:

Aim
To write a python program to circulate the values of n variables

Procedure:
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.
Program1
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]

20
Program2

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


list1 = [] for val in range(0,n,1):
ele = int(input("Enter integer : "))
list1.append(ele)
print("Circulating the elements of list ", list1)
for val in range(0,n,1):
ele = list1.pop(0)
list1.append(ele)
print(list1)

Output
Enter number of values : 4
Enter integer : 87
Enter integer : 58
Enter integer : 98
Enter integer : 52
Circulating the elements of list [87, 58, 98, 52]
[58, 98, 52, 87]
[98, 52, 87, 58]
[52, 87, 58, 98]
[87, 58, 98, 52]

Result
Thus circulate the values of n variables program has been executed and verified successfully.

21
Ex.No:2.c
Distance between two points
Date:

Aim
To write a python program to find the distance between two points

Procedure:
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:",Result)

22
Output

Enter the values to find the distance between two points


Enter X1 value: 2
Enter Y1 value: 4
Enter X2 value: 4
Enter Y2 value: 8
Distance between two points:4

Result
Thus the distance between two points program has been executed and verified successfully.

23
Ex.No:3.a
Number Series
Date:

Aim
To write a python program for the Number Series

Fibonacci sequence: 0 1 1 2 3 5 8 13 21 34

Procedure:
Step1: Start the program
Step2: Read the number of terms
Step3: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

24
Number Series: 12+22+…+n2

Procedure:
Step1: Start the program
Step2: Read the number of terms

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.

25
Ex.No:3.b
Number Patterns
Date:

Aim
To write a python program for the Number Patterns

Number Pattern_Type1

Procedure:
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 i

Step4: 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

26
NumberPattern_Type2
Procedure:
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:
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 PatternEnter the number of rows: 5


1
12
123
1234
12345

RESULT:
Thus the number patterns programs have been executed and verified successfully

27
Ex.No:3.c
Pyramid Patterns
Date:

Aim
To write a python program for the Pyramid Patterns

Procedure:
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.

28
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:
Enter number of rows:5
*
***
*****
******

RESULT:
Thus the pyramid pattern program has been executed and verified successfully

29
Ex.No:4.a
Items present in a library
Date:

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

Procedure:

Step1: Start the program


Step2: Initialize the Library list with the following items
'Books','Periodicals','Newspaper','Manuscripts','Maps','Prints','Documents','E
books'
Step3: Process the following from I in Library Display i
Step 4: Add an item to the Library list
Step5: Display all items from Library list
Step 6: Remove index item from Library list
Step 7: Delete items from Library list
Step 8: Insert an item to the Library
Step 9: Stop the program

Program

# declaring a list of items in a Library


library=['Books','Periodicals','Newspaper','Manuscripts','Maps','Prints','Documents',
'E-books']
# printing the complete list
print('Library: ',library)
# printing first element
print('first element: ',library[0])
# printing fourth element
print('fourth element: ',library[3])
# printing list elements from 0th index to 4th index
print('Items in Library from 0 to 4 index: ',library[0: 5])
# printing list -7th or 3rd element from the list
print('3rd or -7th element: ',library[-7])
# appending an element to the list
library.append('Audiobooks')
print('Library list after append(): ',library)
# finding index of a specified element
print('index of \'Newspaper\': ',library.index('Newspaper'))
# sorting the elements of LIst
library.sort()
print('after sorting: ', library);
# popping an element
print('Popped elements is: ',library.pop())

30
print('after pop(): ', library);

# removing specified element


library.remove('Maps')
print('after removing \'Maps\': ',library)
# inserting an element at specified index
# inserting 100 at 2nd index
library.insert(2, 'CDs')
print('after insert: ', library)
# Number of Ekements in Library list
print(' Number of Elements in Library list : ',library.count('Ebooks'))

Output:

Library: ['Books', 'Periodicals', 'Newspaper', 'Manuscripts', 'Maps', 'Prints',


'Documents', 'Ebooks']
first element: Books
fourth element: Manuscripts
Items in Library from 0 to 4 index: ['Books', 'Periodicals',
'Newspaper', 'Manuscripts', 'Maps']
3rd or -7th element: Periodicals
Library list after append(): ['Books', 'Periodicals', 'Newspaper', 'Manuscripts',
'Maps', 'Prints', 'Documents', 'Ebooks', 'Audiobooks']
index of 'Newspaper': 2
after sorting: ['Audiobooks', 'Books', 'Documents', 'Ebooks', 'Manuscripts', 'Maps',
'Newspaper', 'Periodicals', 'Prints']
Popped elements is: Prints
after pop(): ['Audiobooks', 'Books', 'Documents', 'Ebooks', 'Manuscripts', 'Maps',
'Newspaper', 'Periodicals']
after removing 'Maps': ['Audiobooks', 'Books', 'Documents', 'Ebooks',
'Manuscripts', 'Newspaper', 'Periodicals']
after insert: ['Audiobooks', 'Books', 'CDs', 'Documents', 'Ebooks', 'Manuscripts',
'Newspaper', 'Periodicals']
Number of Elements in Library list : 1

Result
Thus the items present in a library program has been executed and verified successfully.

31
Ex.No:4.b
Components of a car
Date:

Aim
To write a python program for components of a car.

Procedure:
STEP 1: Start the program
STEP 2: Create the variable inside that variable assigned the list of elements based on the car using
List and tuple
STEP 3:Using array index to print the items using list and tuple
STEP 4:To print the result using output statement
STEP 5: Stop the program

Program:
print("Components of a car")
print(" --------------- ")
Main_parts=["Chassis","Engine","Auxiliaries"]
Transmission_System=["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)
total_parts.extend(Body)
print("---------------- ")
print("Total components of the car:", len(total_parts))
print("---------------- ")
total_parts. sort()
j=0
for i in total_parts:
j=j+1
print(j,i)

32
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: 9
-----------
1 Auxiliaries
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

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

Procedure:
STEP 1: Start the program
STEP 2: Create the variable and stored the unordered list of elements based on materials Required for
construction of building List and tuple
STEP 3: Using array index to print the items using list and tuple
STEP 4: To print the result using output statement
STEP 5: Stop the program

Program
print("Materials required for construction of a building")
print("Approximate Price:\n1.Cement:16%\n2.Sand:12%\n3.Aggregates:8%\n
4.Steelbars:24%\n5.Bricks:5%\n6.Paints: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",
"Steelbars/Kilogram",
"Bricks/Piece","Paints/Litres","Tiles/Squrefeet","Plumbingitems/meterorpiece","
Electricalitems/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:",min(price))
print("Max:",max(price))
print("Length:",len(price))
print("Sum:",sum(price))
print("Sort:",sorted(price))
print("all()",all(price))
print("any()",any(price))

34
Output
Materials required for construction of a building
Approximate Price:
1.Cement:16%
2.Sand:12%
3.Aggregates:8%
4.Steelbars:24%
5.Bricks:5%
6.Paints:4%
7.Tiles:8%
8.Plumbing items:5%
9.Electricalitems:5%
10.Wooden products:10%
11.Bathroom accessories:3%
Cement/Bag : 410
Sand/Cubicfeet : 50
Aggregates/Cubicfeet : 25
Steelbars/Kilogram : 57
Bricks/Piece : 7
Paints/Litres : 375
Tiles/Squrefeet : 55
Plumbingitems/meterorpiece : 500
Electrical items/meterorpiece : 500
Woodenproducts/squarefeet : 1000
Bathroomaccessories/piece : 1000
-------------------
Cement/Bag : 410
Sand/Cubicfeet : 50
Aggregates/Cubicfeet : 25
Steelbars/Kilogram : 57
Bricks/Piece : 7
Paints/Litres : 375
Tiles/Squrefeet : 55
Plumbingitems/meterorpiece : 500
Electrical items/meterorpiece : 500
Woodenproducts/squarefeet : 1000
Bathroomaccessories/piece : 1000
-----------------
Operations of tuple / list
Min: 7
Max: 1000
Length: 11
Sum: 3979
Sort: [7, 25, 50, 55, 57, 375, 410, 500, 500, 1000, 1000]
all() True
any() True

Result
Thus the Materials required for construction of a building program has been executed and verified
successfully.

35
Ex.No:5.a
Components of a Language
Date:

Aim
To write a python program for language.

Procedure:
STEP 1: Start the program
STEP 2: Create the variable and stored the unordered list of elements based on materials required for
construction of building set and dictionary
STEP 3: Using for loop to list the number of elements and using array index to print the items using
set and dictionary
STEP 4: To print the result using output statement
STEP 5: Stop the program
Program
L1 = {'Pitch', 'Syllabus', 'Script', 'Grammar', 'Sentences'}
L2 = {'Grammar', 'Syllabus', 'Context', 'Words', 'Phonetics'}
# set union
print("Union of L1 and L2 is ",L1 | L2)
# set intersection
print("Intersection of L1 and L2 is ",L1 & L2)
# set difference
print("Difference of L1 and L2 is ",L1 - L2)
# set symmetric difference
print("Symmetric difference of L1 and L2 is ",L1 ^ L2)

Output

Union of L1 and L2 is {'Sentences', 'Script', 'Syllabus', 'Words', 'Grammar',


'Phonetics', 'Context', 'Pitch'}
Intersection of L1 and L2 is {'Syllabus', 'Grammar'}
Difference of L1 and L2 is {'Sentences', 'Script', 'Pitch'}
Symmetric difference of L1 and L2 is {'Sentences', 'Script', 'Phonetics',
'Context', 'Words', 'Pitch'}

Result
Thus the language program has been executed and verified successfully.

36
Ex.No:5.b
Components of an auto mobile
Date:

Aim
To write a python program for Components of an automobile.

Procedure:
STEP 1: Start the program
STEP 2: Create the variable and stored the unordered list of elements based on materials required for
construction of building set and dictionary
STEP 3: Using for loop to list the number of elements and using array index to print the items using
set and dictionary
STEP 4: To print the result using output statement
STEP 5: Stop the program

Program

print("Components of an auto mobile")


print("\n")
print("Dictionary keys")
print(" ")
components={"Engineparts":["piston","cylinderhead","oilpan","enginevalves","combustionchamber","gask
et"],"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("Dictionary items")
print("-----------------")
for i in components.items():
37
print(i)
print("\n")
accessories={"Bumper":["front","back"]}
components.update(accessories)
components['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("Electricalparts")
components. popitem()
print("\n")
print("Dictionary items")
print("---------------")
for i in components.items():
print(i)
components.clear()
print(components)

Output

Components of an auto mobile

Dictionary keys

Engineparts
Drive transmission and steering parts
Suspensionandbrakeparts
Electricalparts
Body and chassis

Dictionary values
------------------
['piston', 'cylinderhead', 'oilpan', 'enginevalves', 'combustionchamber', 'gasket']
['Adjusting nut', 'pit man arm shaft', 'roller bearing', 'steering gear shaft']
['Breakpedal', 'Brakelines', 'Rotors/drums', 'Breakpads', 'Wheel cylinders']
['Battery', 'Starter', 'Alternator', 'Cables']
['Roof panel', 'front panel', ' screen pillar', 'Lights', 'Tyres']

38
Dictionary items
-----------------
('Engineparts', ['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'])

Dictionary items
----------------
('Engineparts', ['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'])
('Bumper', ['front and back'])
6

Dictionary items
---------------
('Engineparts', ['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'])
{}

Result

Thus the components of an automobile program has been executed and verified successfully.

39
Ex.No:5.c
Elements of a civil structure
Date:

Aim
To write a python program for Elements of a civil structure.

Procedure:
STEP 1: Start the program
STEP 2: Create the variable and stored the unordered list of elements based on materials required for
construction of building set and dictionary
STEP 3: Using for loop to list the number of elements and using array index to print the items using
set and dictionary
STEP 4: To print the result using output statement
STEP 5: Stop the program

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.li
ntels\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 raise error
print(elements1)
elements1.discard("hardfloor")
#dataremoved,if item not presentnotraise error

print(elements1)
40
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

{'parapet', 'colum ns', 'roof', 'walls', 'stairs', 'beamsandslabs', 'lintels', 'floors', ' foundation'}

{'parapet', 'colum ns', 'roof', 'dampproof', 'walls', 'stairs', 'beamsandslabs', 'lintels', 'floors', '
foundation'}

{'compound', 'plant s'}

{'parapet', 'plant s', 'colum ns', 'roof', 'dampproof', 'walls', 'stairs', 'beamsandslabs', 'lintels', 'compound',
'floors', ' foundation'}
{'parapet', 'plant s', 'colum ns', 'roof', 'dampproof', 'walls', 'beamsandslabs', 'lintels', 'compound', 'floors',
' foundation'}
{'parapet', 'plant s', 'colum ns', 'roof', 'dampproof', 'walls', 'beamsandslabs', 'lintels', 'compound', 'floors',
' foundation'}
{'plant s', 'colum ns', 'roof', 'dampproof', 'walls', 'beamsandslabs', 'lintels', 'compound', 'floors', '
foundation'}
[' foundation', 'beamsandslabs', 'colum ns', 'compound', 'dampproof', 'floors', 'lintels', 'plant s', 'roof',
'walls']

set operations
41
{'walls', 'beams', 'foundation'}
{'foundation'}
{'walls', 'beams'}
{'floors'}
{'walls', 'beams', 'floors', 'foundation'}

Result
Thus the elements of a civil structure program has been executed and verified successfully.

42
Ex.No:6.a
Factorial
Date:

Aim
To write a python program for factorial.

Procedure:
Step 1:Get a positive integer input (n) from the user.
Step 2:check if the values of n equal to 0 or not if it's zero it will return 1 Otherwise else statement can
be executed
Step 3:Using the below formula, calculate the factorial of a number n*factorial(n-1)
Step 4:Print the output i.e the calculated

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:5
Using functions- The factorial of 5=120

Result

Thus the factorial program has been executed and verified successfully.

43
Ex.No:6.b
Date: Largest number in a list

Aim
To write a python program for Largest number in a list.

Procedure:
Step 1- Declare a function that will find the largest number
Step 2- Use max() method and store the value returned by it in a variable
Step 3- Return the variable
Step 4- Declare and initialize a list or take input
Step 5- Call the function and print the value returned by i

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

Output
Largest element in the list is:500

Result

Thus the largest number in a list program has been executed and verified successfully.

44
Ex.No:6.c
Area of shape
Date:

Aim
To write a python program for area of a shape.

Procedure:
Step 1:Get the input from the user shape’s name.
Step 2:If it exists in our program then we will proceed to find the entered shape’s area according to
their respective formulas.
Step 3:If that shape doesn’t exist then we will print “Sorry!
Step 4:Stop the program

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("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)
elif name=='parallelogram':
b=int(input("Enter parallelogram's base length:"))
h= int(input("Enter parallelogram's height length:"))

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

CalculateShapeArea:
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:2
The area of triangle is 10.0

Result
Thus the area of a shape program has been executed and verified successfully.

46
Ex.No:7.a
String Reverse
Date:

Aim
To write a python program for string reverse.

Procedure:
Step 1: start the program
Step 2: Using function string values of arguments passed in that function
Step 3: python string to accept the negative number using slice operation
Step4: to print the reverse string value by Using reverse method function
Step5: print the result

Program 1
#Using Slice Operation
def rev(string):
string=string[::-1]
return string
s=input("Enter any string:")
print("The Original Stringis:", end="")
print(s)
print("Thereversedstring(Using Slice Operation)is:",end="")
print(rev(s))

Output 1

Enter any string:naveen


The Original Stringis:naveen
Thereversedstring(Using Slice Operation)is:neevan

Program 1
#Using Reversed Function
def rev(string):
string="".join(reversed(string))
return string

s=input("Enter any string:")


print("The Original Stringis:", end="")
print(s)
print("The reversed string(Using Reversed Function)is:",end="")
print(rev(s))
47
Output 1
Enter any string:Naveen
The Original Stringis:Naveen
Thereversedstring(Using Reversed Function)is:neevaN

Result
Thus the String reverse program has been executed and verified successfully.

48
Ex.No:7.b
Date: Palindrome

Aim
To write a python program for palindrome.

Procedure:
Step 1: start the program
Step 2: use the input function to take user input for a string.
Step 3: convert the input string to lowercase using the lower() method.
Step 4: use the reversed() function to obtain the reversed version of the string.
Compare the original string with its reversed version to check if it is a palindrome.
Print whether the string is a palindrome or not.
Step 5: print the result
Program

string=input("Enterthestring:")
string=string.lower()
print(string)
rev_string=reversed(string)
if(list(string)==list(rev_string)):
print(f"Given string{string}isPalindrome.")
else:
print("Givenstring{string}is not Palindrome.")

Output

Enter the string:mam


mam
Given string mam is Palindrome.

Result
Thus the palindrome program has been executed and verified successfully.

49
Ex.No:7.c
Character Count
Date:

Aim

To write a python program for character count.

Procedure:
Step 1: start the program
Step 2: use the input function to take user input for a string.
Step 3: Use the len function to find the total number of characters in the input string..
Step 4: Request the user to input a character using the input function and store it in the variable char.
Step 5: Use the count method to find the number of occurrences of the input character in the string.
Store the result in the variable val.
Step 6: print the count of the entered character.

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:Naveen
Total characters in the given string is 6
Enter a character to count:e
2

Result

Thus the character count program has been executed and verified successfully.

50
Ex.No:7.d
Replacing characters
Date:

Aim
To write a python program for replacing character.

Procedure:
Step 1: Using string.replace(old, new, count)
Step 2 : by using string Parameters to change it old – old substring you want to replace.new – new
substring which would replace the old substring.
Step 3: count – (Optional ) the number of times you want to replace the old substring with the new
substring.
Step 4: To returns a copy of the string where all occurrences of a substring are replaced with another
substring.

Program

string=input("Enter the string:")


str1=input("Enter old string:")
str2=input("Enter replacable string:")
print(string.replace(str1,str2))

Output
Enter the string:Problem Solving and Java Programming
Enter old string:Java
Enter replacable string:Python
Problem Solving and Python Programming

Result
Thus the replacing character program has been executed and verified successfully.

51
Ex.No:8.a
Date: Pandas

Aim
To write a python program for pandas.

Procedure:
Step 1: start the program
Step 2: DataFrame is the key data structure in Pandas. It allows us to store And manipulate tabular
data Step 3: python method of DataFrame has data aligned in rows and columns like the SQL table or
a spreadsheet database
Step 4: using Series: It is a 1-D size-immutable array like structure having homogeneous data in a
python module
Step 5:using max function method to display the maximum ages in a program
Step 6:List of elements can be displayed by using output statement in pandas.
Step 7: stop the program

Program
import pandas as pd
ds1 = pd.Series([2, 4, 6, 8, 10])
ds2 = pd.Series([1, 3, 5, 7, 10])
print("Series1:")
print(ds1)
print("Series2:")
print(ds2)
print("Compare the elements of the said Series:")
print("Equals:")
print(ds1 == ds2)
print("Greater than:")
print(ds1 > ds2)
print("Less than:")
print(ds1 < ds2)

52
Output

Series1:
0 2
1 4
2 6
3 8
4 10
dtype: int64

Series2:
0 1
1 3
2 5
3 7
4 10
dtype: int64
Compare the elements of the said Series:
Equals:
0 False
1 False
2 False
3 False
4 True
dtype: bool
Greater than:
0 True
1 True
2 True
3 True
4 False
dtype: bool
Less than:
0 False
1 False
2 False
3 False
4 False
dtype: bool

Result

Thus the pandas program has been executed and verified successfully.

53
Ex.No:8.b
Numpy
Date:

Aim
To write a python program for numpy.

Procedure
Step 1:start the program
Step 2:to create the package of numpy in python and using array index in numpy for numerical
calculation Step 3:to create the array index inside that index to assign the values in that dimension
Step 4: Declare the method function of arrange statement can be used in that program
Step 5: By using output statement we can print the result

Program
import numpy as np
a = np.arange(6)
print("range 6",a)
a2 = a[np.newaxis, :]
print("newaxis:",a2)
print("Shape",a2.shape)
#Array Creation and functions:
a1 = np.array([1, 2, 3, 4, 5, 6])
print("Array")
print(a1)
a2 = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print("2D Array")
print(a2)
a3 = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print("3D Array")
print(a3)
print("access 0th Index in 3D",a3[0])
print("access 1st Index in 3D",a3[1])
print("print Zeros",np.zeros(2))
print("print Ones",np.ones(2))
print("range 4",np.arange(4))
print("range",np.arange(2, 9, 2))
print("linespace",np.linspace(0, 10, num=5))
x = np.ones(2, dtype=np.int64)

54
print("print Integer 1's",x)
arr = np.array([2, 1, 5, 3, 7, 4, 6, 8])
print("Array",arr)
print("Sort",np.sort(arr))
a = np.array([1, 2, 3, 4])
print("a:",a)
b = np.array([5, 6, 7, 8])
print("b:",b)
print("concatenate a and b",np.concatenate((a, b)))
#Array Dimensions:
array_example = np.array([[[0, 1, 2, 3], [4, 5, 6, 7]], [[0, 1, 2, 3], [4, 5, 6, 7]],
[[0 ,1 ,2, 3], [4, 5, 6, 7]]])
print("Array Dimension")
print(array_example)
print("number of dimension:",array_example.ndim)
print("Size:",array_example.size)
print("Shape:",array_example.shape)
a = np.arange(6)
print("a:",a)
b=a.reshape(3, 2)
print("reshape")
print(b)
print("new shape",np.reshape(a, newshape=(1, 6), order='C'))

55
Output
range 6 [0 1 2 3 4 5]
newaxis: [[0 1 2 3 4 5]]
Shape (1, 6)
Array
[1 2 3 4 5 6]
2D Array
[[1 2 3 4]
[5 6 7 8]]
3D Array
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
access 0th Index in 3D [1 2 3 4]
access 1st Index in 3D [5 6 7 8]
print Zeros [0. 0.]
print Ones [1. 1.]
range 4 [0 1 2 3]
range [2 4 6 8]
linespace [ 0. 2.5 5. 7.5 10. ]
print Integer 1's [1 1]
Array [2 1 5 3 7 4 6 8]
Sort [1 2 3 4 5 6 7 8]
a: [1 2 3 4]
b: [5 6 7 8]

56
concatenate a and b [1 2 3 4 5 6 7 8]
Array Dimension
[[[0 1 2 3]
[4 5 6 7]]

[[0 1 2 3]
[4 5 6 7]]

[[0 1 2 3]
[4 5 6 7]]]
number of dimension: 3
Size: 24
Shape: (3, 2, 4)
a: [0 1 2 3 4 5]
reshape
[[0 1]
[2 3]
[4 5]]
new shape [[0 1 2 3 4 5]]

Result
Thus the numpy program has been executed and verified successfully.

57
Ex.No:8.c
Matplotlib
Date:

Aim
To write a python program for matplotlib.

Procedure:
Step 1:start the program
Step 2: It divided the circle into 4 sectors or slices which represents the respective category(playing,
sleeping, eating and working) along with the percentage they hold.
Step 3:Now, if you have noticed these slices adds up to 24 hrs, but the calculation of pie slices is done
automatically .
Step 4:In this way, pie charts are calculates the percentage or the slice of the pie in same way using
area plot etc using matplotlib
Step 5:stop the program

1.Program
import matplotlib.pyplot as plt
days = [1,2,3,4,5]
sleeping =[7,8,6,11,7]
eating = [2,3,4,3,2]
working =[7,8,7,2,2]
playing = [8,5,7,8,13]
slices = [7,2,2,13]
activities = ['sleeping','eating','working','playing']
cols = ['c','m','r','b']
plt.pie(slices,labels=activities, colors=cols,
startangle=90,
shadow= True,
explode=(0,0.1,0,0),
autopct='%1.1f%%')
plt.title('Pie Plot')
plt.show()

58
Output

2.Program

import matplotlib.pyplot as plt


import numpy as np
plt.style.use('_mpl-gallery')
x = np.linspace(0, 10, 100)
y = 4 + 2 * np.sin(2 * x)
fig, ax = plt.subplots()
ax.plot(x, y, linewidth=2.0)
ax.set(xlim=(0, 8), xticks=np.arange(1, 8), ylim=(0, 8), yticks=np.arange(1, 8))
plt.show()

59
Output

Result

Thus the matplotlib program has been executed and verified successfully.

60
Ex.No:8.d
Scipy

Date:

Aim
To write a python program for scipy.

Procedure:
Step 1:Start the program
Step 2: The SciPy library consists of a subpackage named scipy.interpolate that consists of spline
functions and classes, one-dimensional and multi-dimensional (univariate and multivariate)
interpolation classes, etc.
Step 3:To import the package of np in a program and create x,x1,y,y1 identifier inside that assign the
np function
Step 4: SciPy provides interp1d function that can be utilized to produce univariate interpolation
Step 5: Stop the program

1.Program
from scipy import constants
print("Minute:",constants.minute)
print("Hour:",constants.hour)
print("Day:",constants.day)
print("Week:",constants.week)
print("Year:",constants.year)
print("Julian:",constants.Julian_year)
print("Kilo:",constants.kilo)
#printingthekilometerunit(inmeters)print(constants.gram)
#printin
gthegramunit(inkilograms)print(constants.mph)
#printingthe miles-per- hour unit (in meters per seconds)
print("Inch:",constants.inch)

Output
Minute: 60.0
Hour: 3600.0
Day: 86400.0
Week: 604800.0
Year: 31536000.0
Julian: 31557600.0
Kilo: 1000.0
Inch: 0.0254

61
2.Program
import matplotlib.pyplot as plt
from scipy import interpolate
import numpy as np
x = np.arange(5, 20)
y = np.exp(x/3.0)
f = interpolate.interp1d(x, y)
x1 = np.arange(6, 12)
y1 = f(x1) # use interpolation function returned by `interp1d`
plt.plot(x, y, 'o', x1, y1, '--')
plt.show()
Output

Result

Thus the scipy program has been executed and verified successfully.

62
Ex.No:9.a
Copy from one file to another
Date:

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

Procedure:
Step 1:Start the program
Step 2: Import the copyfile function from the shutil module.
Step 3: Request the user to input the source and destination filenames.
Step 4: Use the copyfile function to copy the content of the source file to the destination file.
Step 5: Open the destination file, read its contents, print them, and then close the file.
Step 6: Stop the program

Program1
import shutil
original = r'C:\Users\Hp\Desktop\naveen.txt'
target = r'C:\Users\Hp\Desktop\kumar.txt'
shutil.copyfile(original, target)
print("File copied successfully!")
c = open(target, "r")
print(c.read())
c.close()

Output
File copied successfully!
hello! Problem Solving and Python Programming I CSE 'a'
Program2
from shutil import copyfile
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()
63
Output
Source File Name:
naveen.txt
hello! Problem Solving and Python Programming I CSE 'a'
Enter source filename: C:\Users\Hp\Desktop\naveen.txt
Enter destination filename:C:\Users\Hp\Desktop\kumar.txt
File copied successfully!
hello! Problem Solving and Python Programming I CSE 'a'

Result
Thus the Copy from one file to another program has been executed and verified successfully

64
Ex.No:9.b

Word count
Date:

Aim
Write a python program to implement word count in File operations in python

Procedure:
Step 1: Open and create the txt file with some statements
Step 2: To save that file with the extension of txt file
Step3 : Now to count the the lenghth of word in a file.
Step 4: To display the word count in a target file
Program
file =open(r"C:\Users\Hp\Desktop\kumar.txt","rt")
data = file.read()
print(data)
words = data.split()
print('Number of words in text file :', len(words))
Output
hello! Problem Solving and Python Programming I CSE 'a'
Number of words in text file : 9

Result
Thus the word count program has been executed and verified successfully.

65
Ex.No:9.c
Longest word
Date:

Aim
To write a python program for longest word.

Procedure:
Step 1: Open and create the txt file with some statements
Step 2: To save that file with the extension of txt file
Step3 : Now to count the longest of word in a file.
Step 4: To display the longest word in a target file

Program
def longest_word(count):
with open(count, 'r') as infile:
words = infile.read().split()
print(words)
max_len = len(max(words, key=len))
return [word for word in words if len(word) == max_len]
print("lognest word",longest_word(r'C:\Users\Hp\Desktop\naveen.txt'))

Output
['hello!', 'Problem', 'Solving', 'and', 'Python', 'Programming', 'I', 'CSE', "'a'"]
lognest word ['Programming']

Result

Thus the longest word program has been executed and verified successfully.

66
Ex.No:10.a
Divide by zero error
Date:

Aim:
To Write a exception handling program using python to depict the divide by zero
error.

Procedure:
step 1: start the program
step 2: The try block tests the statement of error. The except block handle the error.
step 3: A single try statement can have multiple except statements. This is useful
when the try block contains statements that may throw different types of exceptions
step 4: To create the two identifier name and enter the values
step 5:by using division operation and if there is any error in that try block raising the
error in that block
step 6: otherwise it display the result

Program 1:

marks = 10000
a = marks / 0
print(a)

Output:
ZeroDivisionError: division by zero

Program 2:
a = int(input("Enter a="))
b = int(input("Enter b="))

try:
c = ((a + b) / (a - b))

except ZeroDivisionError:
print("a/b results in division by zero")

else:
print(c)

Output:
Entre a=4
Entre b=6
-5.0

Result:
Thus the exception handling program using python to depict the divide by zero error.
was successfully executed and verified
67
Ex.No:10.b
Voter’s age validity
Date:

Aim:
To Write a exception handling program using python to depict the voters eligibility

Procedure:
Step 1: Start the program
Step 2:Read the input file which contains names and age by using try catch exception
handling method
Step 3:To Check the age of the person. if the age is greater than 18 then write the
name into voter list otherwise write the name into non voter list.
Step 4: Stop the program

Program

def main():
#get the age
try:
age=int(input("Enter your age"))
if age>18:
print("Eligible to vote")
else:
print("Not eligible to vote")
except:
print("age must be a valid number")
main()

Output
Enter your age45
Eligible to vote

Result

Thus the voter’s age validity program has been executed and verified successfully

68
Ex.No:10.C
Student mark range validation
Date:

Aim
To Implementing real-time/technical applications using Exception handling.- student
mark range validation

Procedure:
Step 1: Start the program
Step 2:By using function to get the input from the user
Step 3:Using Exception handling in that c if statement can be used to check the mark
range in the program
Step 4:Given data is not valid it will throw the IOexception in the process
Step 5: Stop the program

Program

def main():
try:
python=int(input("Enter marks of the Python subject: "))
print("Python Subject Grade", end=" ")
if(python>=90):
print("Grade: O")
elif(python>=80 and python<90):
print("Grade:A+")
elif(python>=70 and python<80):
print("Grade:A")
elif(python>=60 and python<70):
print("Grade:B+")
elif(python>=50 and python<60):
print("Grade:B")
else:
print("Grade: U")
except:
print("Entered data is wrong, Try Again")
finally:
print("Thank you")

main()

69
Output
Enter marks of the Python subject: 45
Python Subject Grade Grade: U
Thank you

Enter marks of the Python subject: a


Entered data is wrong, Try Again
Thank you

Result

Thus the student mark range validation program has been executed and verified
successfully.

70
Ex. No.11
Exploring Pygame tool.
Date:

Aim:
To write procedure for installing pygame in python

Procedure:

PyGame is a library of python language. It is used to develop 2-D games and is a


platform where you can set python modules to develop a game. It is a user-friendly platform
that helps to build games quickly and easily.
Step 1: Check for Python Installation In order to install Pygame, Python must be
installed already in your system. To check whether Python is installed or not in your system,
open the command prompt and give the command as shown below.

Step 2: Check for PIP installation PIP is a tool that is used to install python packages.
PIP is automatically installed with Python 2.7. 9+ and Python 3.4+. Open the command
prompt and enter the command shown below to check whether pip is installed or not

71
Step 3: Install Pygame To install Pygame, open the command prompt and give the command
as shown below:
cd C:\Program Files\Python312\Scripts
pip install pygame

Step 4: Check Whether PyGame is Working or not Now open a new terminal and import the
Pygame library to see whether it is working fine or not in our system. The library is imported
successfully means we got success

Result:
Thus, the pygame was successfully installed

72
Ex.No:12
Simulate bouncing ball using pygame
Date:

Aim
To write a python program for simulate bouncing ball using pygame.

Procedure:
Step1: Start the program
Step 2:The pygame.display.set_mode() function returns the surface object for the
window. This function accepts the width and height of the screen as arguments.
Step 3:To set the caption of the window, call the pygame.display.set_caption()
function. opened the image using the pygame.image.load() method and set the ball
rectangle area boundary using the get_rect() method.
Step 4:The fill() method is used to fill the surface with a background color.
Step 5:pygame flip() method to make all images visible.
Step 6: Stop the program

Program:
import pygame
# initialize pygame
pygame.init()

# define width of screen


width = 1000
# define height of screen
height = 600
screen_res = (width, height)

pygame.display.set_caption("GFG Bouncing game")


screen = pygame.display.set_mode(screen_res)

# define colors
red = (255, 0, 0)
black = (0, 0, 0)

# define ball
ball_obj = pygame.draw.circle(surface=screen, color=red, center=[100, 100], radius=40)

73
# define speed of ball
# speed = [X direction speed, Y direction speed]
speed = [1, 1]

# game loop
while True:
# event loop
for event in pygame.event.get():
# check if a user wants to exit the game or not
if event.type == pygame.QUIT:
exit()

# fill black color on screen


screen.fill(black)

# move the ball


# Let center of the ball is (100,100) and the speed is (1,1)
ball_obj = ball_obj.move(speed)
# Now center of the ball is (101,101)
# In this way our wall will move

# if ball goes out of screen then change direction of movement


if ball_obj.left <= 0 or ball_obj.right >= width:
speed[0] = -speed[0]
if ball_obj.top <= 0 or ball_obj.bottom >= height:
speed[1] = -speed[1]

# draw ball at new centers that are obtained after moving ball_obj
pygame.draw.circle(surface=screen, color=red,
center=ball_obj.center, radius=40)

# update screen
pygame.display.flip()

74
Output:

Ball is bouncing on Display Screen

Result

Thus the simulate bouncing ball using pygame program has been executed and
verified successfully.

75

You might also like