KEMBAR78
Python Lab (1) 2 | PDF | Area | String (Computer Science)
0% found this document useful (0 votes)
12 views103 pages

Python Lab (1) 2

The document is a practical record notebook for the GE3171 Problem Solving and Python Programming Laboratory at Indira Institute of Engineering & Technology. It includes various experiments, algorithms, pseudocode, and flowcharts related to programming tasks such as electricity billing, retail shop billing, and Python programs for variable manipulation and distance calculation. The record is intended for students of the Computer Science and Engineering department for their practical examinations during the academic year 2024-2025.

Uploaded by

yaminishrvani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views103 pages

Python Lab (1) 2

The document is a practical record notebook for the GE3171 Problem Solving and Python Programming Laboratory at Indira Institute of Engineering & Technology. It includes various experiments, algorithms, pseudocode, and flowcharts related to programming tasks such as electricity billing, retail shop billing, and Python programs for variable manipulation and distance calculation. The record is intended for students of the Computer Science and Engineering department for their practical examinations during the academic year 2024-2025.

Uploaded by

yaminishrvani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 103

INDIRA INSTITUTE OF ENGINEERING &TECHNOLOGY

PANDUR, THIRUVALLUR

PRACTICAL RECORD NOTE BOOK

ANNA UNIVERSITY CHENNAI

GE3171-PROBLEM SOLVING AND PYTHON PROGRAMMING


LABORATORY

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


INDIRA INSTITUTE OF ENGINEERING &TECHNOLOGY
Pandur, Thiruvallur – 631 203

University Register No:

CERTIFICATE
Certified to be bonafide record of work done by _______________ on 1ST Semester
BE/B.TECH ( ) in the GE3171-PROBLEM SOLVING AND PYTHON
PROGRAMMING LABORATORY during the academic year 2024-2025.

FACULTY-IN-CHARGE HEAD OF THE DEPARTMENT

Submitted for the University Practical Examination held on

Internal Examiner External Examiner


INDEX

Page
S. No. Date Name of the Experiment Sign
No.

1a.

1b.

1c.

1d.

1e

1f.

2a.

2b.

2c.

3a.

3b.

3c.
Page
S. No. Date Name of the Experiment Sign
No.

4a.

4b.

4c.

5a.

5b.

5c.

6a.

6b.

6c.

7a.

7b.

7c.

7d.

8a.
Page
S. No. Date Name of the Experiment Sign
No.

8b.

8c.

8d.

9a.

9b.

9c.

10a.

10b.

10c.

11.

12a.

12b.
1a. ELECTRICITY BILLING FLOWCHART

Date:

AIM:

To develop a flow chart for Electricity Billing

ALGORITHM:

Step 1: Start
Step 2: Read consumer details
Step 3: Read previous month reading
Step 4: Read current month reading
Step 5: Calculate the units consumed by subtracting the current month reading from the
previous month reading
Step 6: Calculate the bill amount by splitting the units consumed based on the tariff
Step 7: Add all the unit prices based on the tariff slabs to get the total amount
Step 8: Print the consumer details
Step 9: Print the total bill amount
Step 10: Stop

PSEUDOCODE:

READ customer details


READ previous month reading, current month reading
CALCULATE units_consumed = current month reading - previous month reading
CALCULATE total amount = (first 100 units * 1) + (101 to 200 units * 2.5) + (201 to 500
units * 4) + (from 501 units * 6)
PRINT consumer details
PRINT total amount

1
FLOW CHART:

RESULT:
The flowchart for generating electricity bill for consumers was successfully designed.

2
1b. RETAIL SHOP BILLING FLOWCHART

Date:

AIM:

To develop a flow chart for Retail Shop Billing

ALGORITHM:

Step 1: Start
Step 2: Declare item1’s unit price
Step 3: Get the unit price of item1 from the consumer
Step 4: Calculate total price of unit1 by multiplying unit price of item1 and its quantity
Step 5: Declare item2’s unit price
Step 6: Get the unit price of item2 from the consumer
Step 7: Calculate total price of unit2 by multiplying unit price of item1 and its quantity
Step 8: Declare item3’s unit price
Step 9: Get the unit price of item3 from the consumer
Step 10: Calculate total price of unit3 by multiplying unit price of item1 and its quantity
Step 11: Calculate the total amount by adding up all the total price of the items
Step 12: Display the total amount
Step 13: Stop

PSUEDOCODE

DECLARE the unit price of item1, item2 and item3


READ the quantity of item1, item2 and item3
CALCULATE the total cost = (unit price of item1 * item1 quantity) + (unit price of item2 *
item2 quantity) + (unit price of item3 * item3 quantity)
DISPLAY the total cost

3
FLOW CHART

RESULT:
The flowchart for generating retail shop bill was successfully designed.

4
1c. PRINTING SINE SERIES FLOWCHART

Date:

AIM:

To develop a flow chart for printing the sine series

ALGORITHM:

Step 1: Start
Step 2: Store the initial value of the sine series
Step 3: Store the ending value of the sine series
Step 4: Store the increment value for the next sine series to be calculated
Step 5: Start from the initial value
Step 6: Increase each count by the increment value
Step 7: Calculate the sine value for each number by converting them into radians
Step 8: Display the sine value for the current number
Step 9: Repeat steps 6, 7 & 8 till the ending value is reached
Step 10: Stop

PSEUDOCODE

DECLARE start value, end value, increment


LOOP from start value TILL end value BY increment
READ current value

CALCULATE radian value x = current value * ( 22 )


7

 x1   x3   x5   x7 
CALCULATE sin(x) =     ...
 1!   3!   5!   7! 
       

DISPLAY sin(x)
END LOOP

5
FLOW CHART

RESULT:
The flowchart for generating printing sine series was successfully designed.

6
1d. CALCULATE WEIGHT OF A MOTORCYCLE FLOWCHART

Date:

AIM:

To develop a flow chart to calculate the weight of a motorcycle

ALGORITHM:

Step 1: Start
Step 2: Get the cc of the motorcycle from the user
Step 3: Based upon the cc of the motorcycle, assign the weight of the motorcycle
Step 4: Display the weight in kilogram, of the motorcycle
Step 5: Stop

PSEUDOCODE:

READ cc
IF cc < 300 THEN weight = 350
ELSE
IF cc >= 300 and cc < 500 THEN weight = 410
ELSE
IF cc >= 500 and cc < 900 THEN weight = 430
ELSE
IF cc >= 900 and cc < 1100 THEN weight = 500
ELSE
IF cc >= 1100 THEN weight = 610
END IF
DISPLAY weight

7
FLOW CHART

RESULT:
The flowchart for generating the weight of a motorcycle was successfully designed.

8
1e. CALCULATING THE WEIGHT OF A STEEL BAR FLOWCHART

Date:

AIM:

To develop a flow chart for calculating the weight of a steel bar

ALGORITHM:

Step 1: Start
Step 2: Get the diameter of the steel bar in mm from the user
Step 3: Get the length of the steel bar in meters
Step 4: Calculate the weight of the steel bar
Step 5: Display the weight of the steel bar
Step 6: Stop

PSEUDOCODE:

READ the diameter (D)


READ the length (L)
CALCULATE weight (W) = D * D * L / 162
DISPLAY weight

9
FLOW CHART

RESULT:
The flowchart for calculating the weight of a steel bar was successfully designed.

10
1f. THREE PHASE CURRENT CALCULATION FLOWCHART

Date:

AIM:

To develop a flow chart for calculating the current in a 3 phase supply

ALGORITHM:

Step 1: Start
Step 2: Get the line to line voltage
Step 3: Get the power factor value
Step 4: Calculate the current in the circuit
Step 5: Display the current value
Step 6: Stop

PSEUDOCODE:

READ line to line voltage (VLL)


READ power factor (PF)
CALCULATE VLN = VLN / √3
CALCULATE kVA = 12 / PF
CALCULATE current = (kVA * 1000) / VLN
DISPLAY current

11
FLOW CHART

RESULT:
The flowchart for calculating current in a 3 phase supply was successfully designed.

12
2a. PYTHON PROGRAM TO EXCHANGE THE VALUES OF TWO VARIABLES

Date:

AIM:

To write a write a Python program using simple statements and expressions to exchange the
value of two variables.

ALGORITHM:

Step 1: Start
Step 2: Get the first number (num1) from the user
Step 3: Get the second number (num2) from the user
Step 4: Use a temporary variable (temp) to store the value of num1
Step 5: Store the value of num2 in num1
Step 6: Store the value of temp in num2
Step 7: Print the swapped values of num1 and num2
Step 8: Stop

PROGRAM:

num1 = int(input("Enter the First Number : "))


num2 = int(input("Enter the Second Number : "))
temp = 0
temp = num1
num1 = num2
num2 = temp
print("\n")
print("The swapped First Number is : " , num1)
print("The swapped Second Number is : " , num2)

13
OUTPUT:

Enter the First Number : 10


Enter the Second Number : 25

The swapped First Number is : 25


The swapped Second Number is : 10

RESULT:

The Python program to exchange the values of two variables was successfully executed.

14
2b. CIRCULATE THE VALUES OF n VARIABLES

Date:

AIM:

To write a Python program using simple statements and expressions to circulate the values
of n variables

ALGORITHM:

Step 1: Start
Step 2: Get the number of elements ‘n; from the user
Step 3: Initialize a list
Step 4: Get the values for all the ‘n’ elements from the user and store them in the list
Step 5: Repeat the loop for ‘n’ times
Step 5.1: Pop the first element from the list
Step 5.2: Add this element to the end of the list
Step 5.3: Display the contents of the list
Step 6: Stop

PROGRAM:

count = int(input("Enter the number of elements : "))


list_nos = []

for x in range(count):
elements = int(input("Enter the elements : "))
list_nos.append(elements)

print("The initial elements of the list are : " , list_nos)


print("Circulating the values of the variables:")

15
for x in range(count):
pop_element = list_nos.pop(0)
list_nos.append(pop_element)
print(list_nos)

OUTPUT:

Enter the number of elements : 4


Enter the elements : 10
Enter the elements : 20
Enter the elements : 30
Enter the elements : 40
The initial elements of the list are : [10, 20, 30, 40]

Circulating the values of the variables:

[20, 30, 40, 10]


[30, 40, 10, 20]
[40, 10, 20, 30]
[10, 20, 30, 40]

RESULT:

The Python program to circulate the values of ‘n’ variables was successfully executed.

16
2c. CALCULATE THE DISTANCE BETWEEN TWO POINTS

Date:

AIM:

To write a Python program using simple statements and expressions to calculate the
distance between two points

ALGORITHM:

Step 1: Start
Step 2: Get the coordinate values of the first point (x1, y1)
Step 3: Get the coordinate values of the second point (x2, y2)
Step 4: Calculate the distance between the two points using the formula:

(x2  x1 ) 2 (y2  y1 )2

Step 5: Display the result rounded off to 4 decimal places


Step 6: Stop

PROGRAM:

import math

x1 = int(input("Enter the value for x1 : "))


y1 = int(input("Enter the value for y1 : "))
x2 = int(input("Enter the value for x2 : "))
y2 = int(input("Enter the value for y2 : "))

dist = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)


dist_round = round(dist, 4)

print(f"The distance between points ({x1}, {y1}) and ({x2}, {y2}) is :


{dist_round}")

17
OUTPUT:

Enter the value for x1 : 50


Enter the value for y1 : 20
Enter the value for x2 : 30
Enter the value for y2 : 10
The distance between points (50, 20) and (30, 10) is : 22.3607

RESULT:

The Python program to calculate the distance between two points was successfully executed.

18
3a. PYTHON PROGRAM TO PRINT NUMBER SERIES

Date:

AIM:

To write a Python program using conditionals and iterative loops to print a number series

ALGORITHM:

Step 1: Start
Step 2: Get the starting value of the number series
Step 3: Get the number of terms in the series
Step 4: Get the difference between two consecutive terms in the number series
Step 5: Calculate the end term of the series using the formula:
end = start number + number of terms + difference
Step 6: Loop till the end term by adding the difference to each consecutive terms generated
Step 7: Display the number series
Step 8: Stop

PROGRAM:

start = int(input("Enter the starting value : "))


no_terms = int(input("Enter the number of terms : "))
diff = int(input("Enter the difference between the terms : "))

end = start + no_terms * diff

print("\nThe terms in the series are :")

for x in range(start, end, diff):


print(x, end=" ")

19
OUTPUT:

Enter the starting value : 10


Enter the number of terms : 8
Enter the difference between the terms : 5

The terms in the series are :


10 15 20 25 30 35 40 45

RESULT:

The Python program to calculate the number series was successfully executed.

20
3b. PYTHON PROGRAM TO PRINT NUMBER PATTERN

Date:

AIM:

To write a Python program using conditionals and iterative loops to print a number pattern

ALGORITHM:

Step 1: Start
Step 2: Get the height of the number pattern
Step 3: Repeat until the height of the pattern
Step 3.1: For each loop start from 1
Step 3.2: Add terms one more than the previous term by incrementing each previous
number in the pattern by 1
Step 4: Stop

PROGRAM:

pattern_ht = int(input("Enter the height of the pattern : "))

for rows in range(0, pattern_ht):


print()
for terms in range(0, rows+1):
print(terms+1, end=" ")

21
OUTPUT:

Enter the height of the pattern : 8

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8

RESULT:

The Python program to print the number pattern was successfully executed.

22
3c. PYTHON PROGRAM TO PRINT PYRAMID PATTERN

Date:

AIM:

To write a Python program using conditionals and iterative loops to print a pyramid pattern

ALGORITHM:

Step 1: Start
Step 2: Get the height of the pyramid
Step 3: Repeat until the height of the pyramid is reached, starting from 1
Step 3.1: Print the pattern in each row
Step 3.2: For each successive row align and print the pattern with one count more than
the previous row count
Step 4: Stop

PROGRAM:

pyramid_ht = int(input("Enter the height of the pyramid : "))

print()
k = 2 * pyramid_ht - 2
for i in range(0, pyramid_ht):
for j in range(0, k):
print(end=" ")
k = k - 1
for j in range(0, i+1):
print("*", end=" ")
print()

23
OUTPUT:

Enter the height of the pyramid : 8

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

RESULT:

The Python program to print the pyramid pattern was successfully executed.

24
4a. IMPLEMENTING ITEMS PRESENT IN A LIBRARY USING LISTS

Date:

AIM:

To write a Python program to implement real time applications using Lists to implement the
items present in a library

ALGORITHM:

Step 1: Start
Step 2: Create an empty list
Step 3: Get the choice from the user
Step 4: If choice is 1, then get the name of the new book and add it to the list
Step 5: If choice is 2, then remove the last added book from the list
Step 6: If choice is 3, then display all the books present in the list
Step 7: If choice is 0, then exit
Step 8: Stop

PROGRAM:

book_list = []

print ("Library Management System\n")


print ("1. Add New Book")
print ("2. Remove Last Book")
print ("3. Display Book List")
print ("0. Exit")

choice = True

while(choice != 0):
choice = int(input("\nEnter your Choice : "))

25
if (choice == 1):
book_name = input("Enter the name of the Book : ")
book_list.append(book_name)
print(book_list)
elif (choice == 2):
if (len(book_list) > 0):
book_list.pop()
print(book_list)
else:
print ("The Book List is EMPTY")
elif (choice == 3):
print(book_list)
elif (choice == 0):
print("Thank You!")

OUTPUT:

Library Management System

1. Add New Book


2. Remove Last Book
3. Display Book List
0. Exit

Enter your Choice : 1


Enter the name of the Book : Python Programming
['Python Programming']

Enter your Choice : 1


Enter the name of the Book : C++ Unleashed

26
['Python Programming', 'C++ Unleashed']

Enter your Choice : 1


Enter the name of the Book : Java Complete Reference
['Python Programming', 'C++ Unleashed', 'Java Complete Reference']

Enter your Choice : 1


Enter the name of the Book : HTML Black Book
['Python Programming', 'C++ Unleashed', 'Java Complete Reference', 'HTML Black
Book']

Enter your Choice : 2


['Python Programming', 'C++ Unleashed', 'Java Complete Reference']

Enter your Choice : 2


['Python Programming', 'C++ Unleashed']

Enter your Choice : 3


['Python Programming', 'C++ Unleashed']

Enter your Choice : 0


Thank You!

RESULT:

The Python program to implement items present in a library using lists was successfully
executed.

27
4b. IMPLEMENTING COMPONENTS PRESENT IN A CAR USING LISTS

Date:

AIM:

To write a Python program to implement technical applications using Lists to implement the
components present in a car

ALGORITHM:

Step 1: Start
Step 2: Create an empty list
Step 3: Get the choice from the user
Step 4: If choice is 1, then get the name of the new part and add it to the end of the list
Step 5: If choice is 2, then get the position from the user and remove the part present at
that position
Step 6: If choice is 3, then remove the last added part added to the list
Step 7: If choice is 4, then sort all the parts present in the list
Step 8: If choice is 5, then display all the parts present in the list
Step 9: If choice is 6, then count all the parts present in the list
Step 10: If choice is 0, then exit
Step 11: Stop

PROGRAM:

parts_list = []

print ("Components of a Car\n")


print ("1. Add Part at End")
print ("2. Add Part at Position")
print ("3. Delete Last Part")
print ("4. Sort Part List")

28
print ("5. Display Parts")
print ("6. Count Parts")
print ("0. Exit")

choice = True

while(choice != 0):
choice = int(input("\nEnter your Choice : "))
if (choice == 1):
car_part = input("Enter the name of the Part : ")
parts_list.append(car_part)
print(parts_list)
elif (choice == 2):
car_part = input("Enter the name of the Part : ")
position = int(input("Enter the position of the Part : "))
parts_list.insert(position-1, car_part)
print(parts_list)
elif (choice == 3):
if (len(parts_list) > 0):
parts_list.pop()
print(parts_list)
else:
print ("The Parts List is EMPTY")
elif (choice == 4):
parts_list.sort()
print(parts_list)
elif (choice == 5):
print(parts_list)
elif (choice == 6):

car_part = input("Enter the name of the Part : ")


available = parts_list.count(car_part)

29
print(f"The number of {car_part} available is : {available}")
elif (choice == 0):
print("Thank You!")

OUTPUT:

Components of a Car

1. Add Part at End


2. Add Part at Position
3. Delete Last Part
4. Sort Part List
5. Display Parts
6. Count Parts
0. Exit

Enter your Choice : 1


Enter the name of the Part : Engine
['Engine']

Enter your Choice : 1

Enter the name of the Part : Transmission


['Engine', 'Transmission']

Enter your Choice : 1

Enter the name of the Part : Clutch


['Engine', 'Transmission', 'Clutch']

Enter your Choice : 1


Enter the name of the Part : Gear
['Engine', 'Transmission', 'Clutch', 'Gear']

30
Enter your Choice : 1
Enter the name of the Part : Brake
['Engine', 'Transmission', 'Clutch', 'Gear', 'Brake']

Enter your Choice : 2


Enter the name of the Part : Alternator
Enter the position of the Part : 3
['Engine', 'Transmission', 'Alternator', 'Clutch', 'Gear', 'Brake']

Enter your Choice : 3


['Engine', 'Transmission', 'Alternator', 'Clutch', 'Gear']

Enter your Choice : 4


['Alternator', 'Clutch', 'Engine', 'Gear', 'Transmission']

Enter your Choice : 5


['Alternator', 'Clutch', 'Engine', 'Gear', 'Transmission']

Enter your Choice : 6


Enter the name of the Part : Engine
The number of Engine available is : 1

Enter your Choice : 0


Thank You!

RESULT:

The Python program to implement components present in a car using lists was successfully
executed.

31
4c. IMPLEMENTING MATERIALS REQUIRED FOR CONSTRUCTION OF A
BUILDING USING TUPLES

Date:

AIM:

To write a Python program to implement technical applications using Tuples to implement


materials required for construction of a building

ALGORITHM:

Step 1: Start
Step 2: Create a tuple containing the materials required for constructing a building
Step 3: Get the choice from the user
Step 4: If choice is 1, then display the construction materials from the tuple
Step 5: If choice is 2, then display the total materials that are present
Step 6: If choice is 3, then get the name of the material and print its position in the tuple
Step 7: If choice is 4, then get the name of the material and print whether the material is
available or not

PROGRAM:

materials = ('Bricks', 'Cement', 'Sand', 'Rebar', 'Gravel', 'Water')

print ("Construction Materials\n")


print ("1. Print Construction Materials")
print ("2. Number of Materials in the Tuple")
print ("3. Position of Materials")
print ("4. Availability of Materials")
print ("0. Exit")

choice = True

32
while(choice != 0):
choice = int(input("\nEnter your Choice : "))
if (choice == 1):
print ("\nMaterials used in construction are :")
for x in materials:
print(x)
elif (choice == 2):
print("\nThe total number of materials :", len(materials))
elif (choice == 3):
choice = input("\nEnter the name of the material : ")
material_position = materials.index(choice) + 1
print (f"The material - {choice} is at position :
{material_position}")
elif (choice == 4):
choice = input("\nEnter the name of the material : ")
if(choice) in materials:
print (choice, "is Available")
else:
print (choice, "is Not Available")
elif (choice == 0):
print("Thank You!")

OUTPUT:

Construction Materials

1. Print Construction Materials


2. Number of Materials in the Tuple
3. Position of Materials
4. Availability of Materials
0. Exit

33
Enter your Choice : 1

Materials used in construction are :


Bricks
Cement
Sand
Rebar
Gravel
Water

Enter your Choice : 2

The total number of materials : 6

Enter your Choice : 3

Enter the name of the material : Sand


The material - Sand is at position : 3

Enter your Choice : 4

Enter the name of the material : Bricks


Bricks is Available

Enter your Choice : 4

Enter the name of the material : Doors


Doors is Not Available

Enter your Choice : 0


Thank You!

34
RESULT:

The Python program to implement materials required for construction of a building was
successfully executed.

35
5a. IMPLEMENTING LANGUAGE OPERATONS USING SETS

Date:

AIM:

To write a Python program for real time implementation of language operations using sets

ALGORITHM:

Step 1: Start
Step 2: Create and populate two sets containing names of programming languages
Step 3: Perform various set operations between these two sets
Step 4: Display the results
Step 5: Stop

PROGRAM:

oop_languages = {"C", "PHP", "Java", "Ruby", "Python"}


funct_languages = {"Clojure", "Haskell", "Python", "Scala"}

print("\nThe OOP languages are:")


print(oop_languages)

print("\nThe Functional languages are:")


print(funct_languages)

print("\nAdding one more Functional language ...")


funct_languages.add("F#")

print("The Updated Functional languages are:")


print(funct_languages)

36
#All Languages present in both the sets
print("\nThe Set Union of both the languages are:")
print(oop_languages | funct_languages)

#Languages that are common in both the sets


print("\nThe Set Intersection of both the languages are:")
print(oop_languages & funct_languages)

#Languages present exclusively in OOP set, but not in Functional set


print("\nThe Set Difference between both the languages are:")
print(oop_languages - funct_languages)

#Languages present in both the sets, but without any common elements
print("\nThe Set Symmetric Difference between both the languages are:")
print(oop_languages ^ funct_languages)

OUTPUT:

The OOP languages are:


{'C', 'Ruby', 'Python', 'Java', 'PHP'}

The Functional languages are:


{'Python', 'Clojure', 'Scala', 'Haskell'}

Adding one more Functional language ...


The Updated Functional languages are:
{'Haskell', 'Python', 'F#', 'Scala', 'Clojure'}

The Set Union of both the languages are:


{'C', 'Ruby', 'Clojure', 'Haskell', 'Python', 'F#', 'Java', 'Scala', 'PHP'}

37
The Set Intersection of both the languages are:
{'Python'}

The Set Difference between both the languages are:


{'PHP', 'C', 'Java', 'Ruby'}

The Set Symmetric Difference between both the languages are:


{'Ruby', 'F#', 'Scala', 'Clojure', 'C', 'Haskell', 'Java', 'PHP'}

RESULT:

The Python program to implement language operations between two sets was successfully
executed.

38
5b. IMPLEMENTING COMPONENTS OF AN AUTOMOBILE USING DICTIONARIES

Date:

AIM:

To write a Python program for technical applications to implement the components of an


automobile by using dictionaries

ALGORITHM:

Step 1: Start
Step 2: Create a dictionary containing the key-value pairs of the automobile components
and their corresponding price
Step 3: Perform various dictionary operations
Step 4: Display the results
Step 5: Stop

PROGRAM:

components_dict = {"Engine":20000, "Brake":8000, "Clutch":12000}

print("\nThe Components of the Dictionary are :")


print(components_dict)

component = input("\nEnter the name of the Part : ")


price = components_dict.get(component)
print(f"The price of {component} is Rs.{price}")

print("\nThe Keys in the Dictionary are :")


x = components_dict.keys()
print(x)

39
print("\nThe Values in the Dictionary are :")
x=components_dict.values()
print(x)

print("\nThe Items in the Dictionary are :")


x = components_dict.items()
print(x)

component = input("\nEnter the name of the New Part : ")


price = int(input("Enter the price of the New Part : "))
print("\nThe Updated Components of the Dictionary are :")
components_dict.update({component:price})
print(components_dict)

OUTPUT:

The Components of the Dictionary are :


{'Engine': 20000, 'Brake': 8000, 'Clutch': 12000}

Enter the name of the Part : Brake


The price of Brake is Rs.8000

The Keys in the Dictionary are :


dict_keys(['Engine', 'Brake', 'Clutch'])

The Values in the Dictionary are :


dict_values([20000, 8000, 12000])

The Items in the Dictionary are :


dict_items([('Engine', 20000), ('Brake', 8000), ('Clutch', 12000)])

40
Enter the name of the New Part : Transmission
Enter the price of the New Part : 15000

The Updated Components of the Dictionary are :


{'Engine': 20000, 'Brake': 8000, 'Clutch': 12000, 'Transmission': 15000}

RESULT:

The Python program to implement the components of an automobile using dictionaries was
successfully executed.

41
5c. IMPLEMENTING ELEMENTS OF A CIVIL STRUCTURE USING DICTIONARIES

Date:

AIM:

To write a Python program for technical applications to implement the elements requires for
constructing a civil structure by using dictionaries

ALGORITHM:

Step 1: Start
Step 2: Create a dictionary containing the key-value pairs of the civil structural elements
and their corresponding IDs
Step 3: Perform various dictionary operations
Step 4: Display the results
Step 5: Stop

PROGRAM:

structures_dict = {"Foundation":1, "Basement":2, "1 Floor":3, "Walls":4,


"Doors":5}

print("\nThe Components of the Dictionary are :")


print(structures_dict)

structure = input("\nEnter the name of the Structure : ")


id = structures_dict.get(structure)
print(f"The ID of {structure} is {id}")

print("\nThe Keys in the Dictionary are :")


x = structures_dict.keys()

42
print(x)

print("\nThe Values in the Dictionary are :")


x=structures_dict.values()
print(x)

print("\nThe Items in the Dictionary are :")


x = structures_dict.items()
print(x)

structure = input("\nEnter name of the New Structure : ")


price = int(input("Enter the ID of the New Structure : "))
print("\nThe Updated Components of the Dictionary are :")
structures_dict.update({structure:price})
print(structures_dict)

OUTPUT:

The Components of the Dictionary are :


{'Foundation': 1, 'Basement': 2, '1 Floor': 3, 'Walls': 4, 'Doors': 5}

Enter the name of the Structure : Walls


The ID of Walls is 4

The Keys in the Dictionary are :


dict_keys(['Foundation', 'Basement', '1 Floor', 'Walls', 'Doors'])

The Values in the Dictionary are :


dict_values([1, 2, 3, 4, 5])

43
The Items in the Dictionary are :
dict_items([('Foundation', 1), ('Basement', 2), ('1 Floor', 3), ('Walls', 4),
('Doors', 5)])

Enter name of the New Structure : Windows


Enter the ID of the New Structure : 6

The Updated Components of the Dictionary are :


{'Foundation': 1, 'Basement': 2, '1 Floor': 3, 'Walls': 4, 'Doors': 5,
'Windows': 6}

RESULT:

The Python program to implement the elements of a civil structure using dictionaries was
successfully executed.

44
6a. FACTORIAL OF A NUMBER USING FUNCTIONS

Date:

AIM:

To write a Python program to calculate the factorial of a number by using functions

ALGORITHM:

Step 1: Start
Step 2: Get the number from the user
Step 3: Define a function to calculate the factorial of the number
Step 4: If the number is either a 0 or a 1 return 1 as the factorial
Step 5: Else calculate the factorial recursively by calling the function and multiplying each
factorial together
Step 6: Display the factorial
Step 7: Stop

PROGRAM:

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

def factorial(number):
return 1 if (number == 0 or number == 1) else number * factorial (number -
1)

answer = factorial(number)

print ("The factorial of ", number, "is : " , answer)

45
OUTPUT:

Enter the number : 5


The factorial of 5 is : 120

Enter the number : 10


The factorial of 10 is : 3628800

RESULT:

The Python program to calculate the factorial of a number using functions was successfully
executed.

46
6b. LARGEST NUMBER IN A LIST USING FUNCTIONS

Date:

AIM:

To write a Python program to find the largest number in a list by using functions

ALGORITHM:

Step 1: Start
Step 2: Create an empty list to store the numbers
Step 3: Get the choice from the user
Step 4: If choice is 1, then get the inputs from the user and store the numbers in the list
Step 5: If choice is 2, then call the function to find the largest number
Step 6: Pass the list as an argument to the function and iterate till the largest number in the
list is found
Step 7: Return the largest number in the list
Step 8: Print the largest number
Step 9: Stop

PROGRAM:

number_list = []

print ("1. Add Numbers")


print ("2. Find Largest Number")
print ("0. Exit")

def find_largest(numbers):
largest = number_list[0]
for x in numbers:

47
if x > largest:
largest = x
return (largest)

choice = True

while(choice != 0):
choice = int(input("\nEnter your Choice : "))
if (choice == 1):
number = int(input("Enter the Number : "))
number_list.append(number)
print(number_list)
elif (choice == 2):
largest_number = find_largest(number_list)
print(largest_number)

elif (choice == 0):


exit

OUTPUT:

1. Add Numbers
2. Find Largest Number
0. Exit

Enter your Choice : 1


Enter the Number : 20
[20]

Enter your Choice : 1


Enter the Number : 30

48
[20, 30]

Enter your Choice : 1


Enter the Number : 15
[20, 30, 15]

Enter your Choice : 1


Enter the Number : 100
[20, 30, 15, 100]

Enter your Choice : 1


Enter the Number : 55
[20, 30, 15, 100, 55]

Enter your Choice : 1


Enter the Number : 5
[20, 30, 15, 100, 55, 5]

Enter your Choice : 2


100

Enter your Choice : 0

RESULT:

The Python program to find the largest number in a list using functions was successfully
executed.

49
6c. CALCULATING AREA OF SHAPES USING FUNCTIONS

Date:

AIM:

To write a Python program to calculate the area of shapes by using functions

ALGORITHM:

Step 1: Start
Step 2: Get the choice from the user
Step 3: If choice is 1, get the measure of sides and calculate the area of the square. Print
the resultant area as output
Step 4: If choice is 2, get the measure of length & breadth and calculate the area of the
rectangle. Print the resultant area as output
Step 5: If choice is 3, get the measure of the base & height and calculate the area of the
triangle. Print the resultant area as output
Step 6: If choice is 4, get the measure of radius and calculate the area of the circle. Print
the resultant area as output
Step 7: Stop

PROGRAM:

print ("1. Area of a Square")


print ("2. Area of a Rectangle")
print ("3. Area of a Triangle")
print ("4. Area of a Circle")
print ("0. Exit")

50
def square_area():
side = float(input("Enter the measure of the side : "))
area = side ** 2
print ("Area of the Square is : " , area, " sq. units")

def rectangle_area():
length = float(input("Enter the measure of the length : "))
breadth = float(input("Enter the measure of the breadth : "))
area = length * breadth

print ("Area of the Rectangle is : " , area, " sq. units")

def triangle_area():
base = float(input("Enter the measure of the base : "))
height = float(input("Enter the measure of the height : "))
area = 0.5 * base * height
print ("Area of the Triangle is : " , area, " sq. units")

def circle_area():
radius = float(input("Enter the measure of the radius : "))
area = 3.14 * (radius ** 2)
print ("Area of the Circle is : " , area, " sq. units")

choice = True

while(choice != 0):
choice = int(input("\nEnter your Choice : "))

if (choice == 1):
square_area()

elif (choice == 2):


rectangle_area()

51
elif (choice == 3):
triangle_area()

elif (choice == 4):


circle_area()

elif (choice == 0):


exit

OUTPUT:

1. Area of a Square
2. Area of a Rectangle
3. Area of a Triangle
4. Area of a Circle
0. Exit

Enter your Choice : 1


Enter the measure of the side : 50
Area of the Square is : 2500.0 sq. units

Enter your Choice : 2


Enter the measure of the length : 20
Enter the measure of the breadth : 80
Area of the Rectangle is : 1600.0 sq. units

Enter your Choice : 3


Enter the measure of the base : 20
Enter the measure of the height : 70
Area of the Triangle is : 700.0 sq. units

52
Enter your Choice : 4
Enter the measure of the radius : 10
Area of the Circle is : 314.0 sq. units

Enter your Choice : 0

RESULT:

The Python program to calculate the area of different shapes by using functions was
successfully executed.

53
7a. IMPLEMENTING REVERSING STRINGS

Date:

AIM:

To write a Python program to reverse a given string

ALGORITHM:

Step 1: Start
Step 2: Get the input string to be reversed from the user
Step 3: Write a function to reverse the string
Step 4: Read the string character by character
Step 5: For each character read, add the next character in front of the previous character
Step 6: Repeat till the end of string is reached
Step 7: Print the reversed string as the output
Step 8: Stop

PROGRAM:

def reverse(s):
str = ""
for i in s:
str = i + str
return str

string = input ("Enter the string : ")

print("The original string is : ", end="")


print(string)

54
print("The reversed string is : ", end="")
print(reverse(string))

OUTPUT:

Enter the string : Python Programming


The original string is : Python Programming
The reversed string is : gnimmargorP nohtyP

RESULT:

The Python program to reverse the given string was successfully executed.

55
7b. IMPLEMENTING PALINDROME CHECK ON STRINGS

Date:

AIM:

To write a Python program to check whether a given string is a palindrome

ALGORITHM:

Step 1: Start
Step 2: Get the input string to be reversed from the user
Step 3: Write a function to reverse the string
Step 4: Read the string character by character
Step 5: For each character read, add the next character in front of the previous character
Step 6: Repeat till the end of string is reached
Step 7: Store the reversed string
Step 8: Write a function that checks if the original string is the same as the reversed string
Step 9: If both string are same, print that the string is a palindrome, else print that the string
is not a palindrome
Step 10: Stop

PROGRAM:

def reverse(s):
reverse_word = ""
for i in s:
reverse_word = i + reverse_word
return reverse_word

def palimdrome(original, reversed):


if (original == reversed):

56
print ("The given word is a Palindrome")
else:
print ("The given word is Not a Palindrome")

original_string = input ("Enter the word : ")


reversed_string = reverse(original_string)

palimdrome (original_string, reversed_string)

OUTPUT:

Enter the word : Malayalam


The given word is a Palindrome

Enter the word : apple


The given word is Not a Palindrome

RESULT:

The Python program to check if a word is a palindrome, was successfully executed.

57
7c. IMPLEMENTING COUNTING CHARACTERS IN A STRING

Date:

AIM:

To write a Python program to count the number of occurrences of a given character in a string

ALGORITHM:

Step 1: Start
Step 2: Get the input string from the user
Step 3: Get the character to be counted
Step 4: Read the string character by character, till end of string is reaches
Step 5: Compare each character of the string with the character to be counted, supplied by
the user
Step 6: If the character matches, increment the counter by 1
Step 7: Print the value of the counter
Step 8: Stop

PROGRAM:

input_string = input("Enter the String : ")


character = input ("Enter the character to be counted (a-z) : ")

count = 0

for i in input_string:
if i == character:
count = count + 1

print (f"The character '{character}' appears {count} times in the string


'{input_string}'")

58
OUTPUT:

Enter the String : if you can dream it, you can do it


Enter the character to be counted (a-z) : i
The character 'i' appears 3 times in the string 'if you can dream it, you can
do it'

RESULT:

The Python program to count the number of occurrences of a given character in a string
was successfully executed.

59
7d. IMPLEMENTING REPLACING CHARACTERS IN STRINGS

Date:

AIM:

To write a Python program to replace a given character in a string

ALGORITHM:

Step 1: Start
Step 2: Get the input string from the user
Step 3: Get the character to be replaced
Step 4: Get the replacement character
Step 5: Use the replace function in Python to replace the original character with the given
replacement character
Step 6: Print the new string
Step 7: Stop

PROGRAM:

input_string = input("Enter the String : ")


find_char = input ("Enter the character to replace (a-z) : ")
replace_char = input ("Enter the character to be replaced with (a-z) : ")

new_string = input_string.replace(find_char, replace_char )

print ("Original String : ", input_string)


print ("Replaced String : ", new_string)

60
OUTPUT:

Enter the String : affect


Enter the character to replace (a-z) : a
Enter the character to be replaced with (a-z) : e
Original String : affect
Replaced String : effect

RESULT:

The Python program to replace a given character in a string was successfully executed.

61
8a. IMPLEMENTING PYTHON STANDARD LIBRARIES - PANDAS

Date:

AIM:

To write a Python program to implement the Pandas library

ALGORITHM:

Step 1: Start
Step 2: Import the pandas library
Step 3: Create three Series in pandas and assign them values
Step 4: Combine the Series into a Python dictionary
Step 5: Create a pandas DataFrame using the created dictionary
Step 6: Print the contents of the DataFrame
Step 7: Stop

PROGRAM:

import pandas as pd

# Define series 1
s1 = pd.Series([1, 3, 4, 5, 6, 2, 9])

# Define series 2
s2 = pd.Series([1.1, 3.5, 4.7, 5.8, 2.9, 9.3])

# Define series 3
s3 = pd.Series(['a', 'b', 'c', 'd', 'e'])

62
# Define Data
Data = {'first':s1, 'second':s2, 'third':s3}

# Create DataFrame
dfseries = pd.DataFrame(Data)

print (dfseries)

OUTPUT:

first second third


0 1 1.1 a
1 3 3.5 b
2 4 4.7 c
3 5 5.8 d
4 6 2.9 e
5 2 9.3 NaN
6 9 NaN NaN

RESULT:

The Python program to implement the Pandas library was successfully executed.

63
8b. IMPLEMENTING PYTHON STANDARD LIBRARIES - NUMPY

Date:

AIM:

To write a Python program to implement the Numpy library

ALGORITHM:

Step 1: Start
Step 2: Import the numpy library
Step 3: Create a numpy array with floats from a given list
Step 4: Create an array from tuples
Step 5: Create a 3x4 matrix with all zeros
Step 6: Create a constant value array with complex types
Step 7: Create an array with random values
Step 8: Create a sequence of integers from 0 to 30 with steps of 5
Step 9: Create a sequence of 10 values in range 0 to 5
Step 10: Reshaping 3x4 array to a 2x2x3 array
Step 11: Flatten a given array
Step 12: Stop

PROGRAM:

import numpy as np

# Creating array from list with type float


a = np.array([[1, 2, 4], [5, 8, 7]], dtype = 'float')
print ("Array created using passed list:\n", a)

64
# Creating array from tuple
b = np.array((1 , 3, 2))
print ("\nArray created using passed tuple:\n", b)

# Creating a 3X4 array with all zeros


c = np.zeros((3, 4))
print ("\nAn array initialized with all zeros:\n", c)

# Create a constant value array of complex type


d = np.full((3, 3), 6, dtype = 'complex')
print ("\nAn array initialized with all 6s. Array type is complex:\n", d)

# Create an array with random values


e = np.random.random((2, 2))
print ("\nA random array:\n", e)

# Create a sequence of integers


# from 0 to 30 with steps of 5
f = np.arange(0, 30, 5)
print ("\nA sequential array with steps of 5:\n", f)

# Create a sequence of 10 values in range 0 to 5


g = np.linspace(0, 5, 10)
print ("\nA sequential array with 10 values between 0 and 5:\n", g)

# Reshaping 3X4 array to 2X2X3 array

arr = np.array([[1, 2, 3, 4],


[5, 2, 4, 2],
[1, 2, 0, 1]])

newarr = arr.reshape(2, 2, 3)

65
print ("\nOriginal array:\n", arr)
print ("Reshaped array:\n", newarr)

# Flatten array
arr = np.array([[1, 2, 3], [4, 5, 6]])
flarr = arr.flatten()

print ("\nOriginal array:\n", arr)


print ("Fattened array:\n", flarr)

OUTPUT:

Array created using passed list:


[[1. 2. 4.]
[5. 8. 7.]]

Array created using passed tuple:


[1 3 2]

An array initialized with all zeros:


[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]

An array initialized with all 6s.Array type is complex:


[[6.+0.j 6.+0.j 6.+0.j]
[6.+0.j 6.+0.j 6.+0.j]
[6.+0.j 6.+0.j 6.+0.j]]

A random array:
[[0.21291071 0.35294952]
[0.12338574 0.67235312]]

66
A sequential array with steps of 5:
[ 0 5 10 15 20 25]

A sequential array with 10 values between0 and 5:


[0. 0.55555556 1.11111111 1.66666667 2.22222222 2.77777778
3.33333333 3.88888889 4.44444444 5. ]

Original array:

[[1 2 3 4]
[5 2 4 2]
[1 2 0 1]]
Reshaped array:
[[[1 2 3]

[4 5 2]]

[[4 2 1]
[2 0 1]]]

Original array:
[[1 2 3]
[4 5 6]]
Fattened array:
[1 2 3 4 5 6]

RESULT:

The Python program to implement the Numpy library was successfully executed.

67
8c. IMPLEMENTING PYTHON STANDARD LIBRARIES - MATPLOTLIB

Date:

AIM:

To write a Python program to implement the Matblotlib library

ALGORITHM:

Step 1: Start
Step 2: Import the pyplot module from the matplotlib library
Step 3: Draw bar graphs using the supplied data
Step 4: Provide legends, x label, y label and title to the bar graph
Step 5: Display the bar graph
Step 6: Stop

PROGRAM:

from matplotlib import pyplot as plt

plt.bar([0.25,1.25,2.25,3.25,4.25],[50,40,70,80,20],
label="Car", color='plum',width=.5)

plt.bar([.75,1.75,2.75,3.75,4.75],[80,20,20,50,60],
label="Bus", color='lightgreen',width=.5)

plt.legend()
plt.xlabel('Days')
plt.ylabel('Distance Travelled (kms)')
plt.title('Travel Information')
plt.show()

68
OUTPUT:

RESULT:

The Python program to implement the Matblotlib library was successfully executed.

69
8d. IMPLEMENTING PYTHON STANDARD LIBRARIES - SCIPY

Date:

AIM:

To write a Python program to implement the Scipy library

ALGORITHM:

Step 1: Start
Step 2: Import the linalg module from the scipy library
Step 3: Import the numpy library
Step 4: Define a 2x2 numpy array
Step 5: Call the eigen function from the scipy library on the numpy array
Step 6: Print the eigen values and the eigen vectors
Step 7: Stop

PROGRAM:

from scipy import linalg


import numpy as np

#Define two dimensional array


arr = np.array([[5,4],[1,2]])

#Pass value into the eig function


eg_val, eg_vect = linalg.eig(arr)

#Get eigenvalues
print ("Eigen Values are : \n")
print(eg_val)

70
#Get eigenvectors
print ("\nEigen Vectors are : \n")
print(eg_vect)

OUTPUT:

Eigen Values are :

[6.+0.j 1.+0.j]

Eigen Vectors are :

[[ 0.9701425 -0.70710678]
[ 0.24253563 0.70710678]]

RESULT:

The Python program to implement the Scipy library was successfully executed.

71
9a. IMPLEMENTING FILE COPYING

Date:

AIM:

To write a Python program to copy the contents of one file to another

ALGORITHM:

Step 1: Start
Step 2: Open the first file to be read in the read mode
Step 3: Create the second file to be written to in the write mode
Step 4: Read the contents of the first file line by line and write it to the second file
Step 5: When all contents are copied, print that the file was successfully copied
Step 6: Stop

PROGRAM:

with open('Ex 09\ReadFileEx09a.txt','r') as firstfile,


open('Ex 09\WriteFileEx09a.txt','w') as secondfile:

for line in firstfile:

secondfile.write(line)

print ("File Succesfully Copied")

OUTPUT:

File Succesfully Copied

72
Ex 09\ReadFileEx09a.txt

Where the mind is without fear and the head is held high;
Where knowledge is free;
Where the world has not been broken up into fragments by narrow domestic
walls;
Where words come from the depths of truth;
Where tireless striving stretches its arms towards perfection;
Where the clear stream of reason has not lost its way into the dreary desert
sands of dead habit;
Where the mind is led forward by thee into ever-widening thought and action;
Into that heaven of freedom, my father, let my country awake.

Ex 09\WriteFileEx09a.txt

Where the mind is without fear and the head is held high;
Where knowledge is free;
Where the world has not been broken up into fragments by narrow domestic
walls;
Where words come from the depths of truth;
Where tireless striving stretches its arms towards perfection;
Where the clear stream of reason has not lost its way into the dreary desert
sands of dead habit;
Where the mind is led forward by thee into ever-widening thought and action;
Into that heaven of freedom, my father, let my country awake.

RESULT:

The Python program to copy the contents of one file to another was successfully executed.

73
9b. IMPLEMENTING WORD COUNT ON A FILE

Date:

AIM:

To write a Python program to count the number of occurrences of each word in a given file

ALGORITHM:

Step 1: Start
Step 2: Import the required Python libraries
Step 3: Open the file in read mode
Step 4: Using regular expressions split the individual words in the file
Step 5: Count the instances of each word using a counter
Step 6: Print each word followed by its occurrence count
Step 7: Stop

PROGRAM:

import re
from collections import Counter
import sys

filename = 'Ex 09\QuoteFileEx09b.txt'

with open(filename) as f:
passage = f.read()

words = re.findall(r'\w+', passage)

cap_words = [word.upper() for word in words]

74
word_counts = Counter(cap_words)

for k, v in word_counts.items():
print (k, '-->' ,v)

OUTPUT:

Ex 09\QuoteFileEx09b.txt

Try to be a rainbow in someones cloud. Do not fear the storm , for the rainbow
is never far behind. If you want to enjoy the rainbow , be prepared to endure
the storm.

TRY --> 1
TO --> 3
BE --> 2
A --> 1
RAINBOW --> 3
IN --> 1
SOMEONES --> 1
CLOUD --> 1
DO --> 1
NOT --> 1
FEAR --> 1
THE --> 4
STORM --> 2
FOR --> 1
IS --> 1
NEVER --> 1
FAR --> 1
BEHIND --> 1
IF --> 1
YOU --> 1

WANT --> 1

75
ENJOY --> 1
PREPARED --> 1
ENDURE --> 1

RESULT:

The Python program to count the number of occurrences of each word in a given file was
successfully executed.

76
9c. IMPLEMENTING FINDING LONGEST WORDS IN FILE

Date:

AIM:

To write a Python program to find the longest words present in a file

ALGORITHM:

Step 1: Start
Step 2: Open the given file in read mode
Step 3: Read the contents of the file and split each individual words
Step 4: Add the words in a list
Step 5: Find the length of all the words in the list
Step 6: Find the longest words present in the list
Step 7: Print all the longest words
Step 8: Stop

PROGRAM:

inputFile = "Ex 09\TextFileEx09c.txt"

with open(inputFile, 'r') as filedata:


wordsList = filedata.read().split()
longestWordLength = len(max(wordsList, key=len))
result = [textword for textword in wordsList if len(textword) ==
longestWordLength]
print("The longest words from the text file are :")
print(result)

filedata.close()

77
OUTPUT:

Ex 09\TextFileEx09c.txt

At the stroke of the midnight hour, when the world sleeps, India will awake to
life and freedom. A moment comes, which comes but rarely in history, when we
step out from the old to the new, when an age ends, and when the soul of a
nation, long suppressed , finds utterance . It is fitting that at this solemn
moment we take the pledge of dedication to the service of India and her people
and to the still larger cause of humanity.

The longest words from the text file are :

['suppressed', 'dedication']

RESULT:

The Python program to find the longest words present in a file was successfully executed.

78
10a. IMPLEMENTING EXCEPTION HANDLING – DIVIDE BY ZERO

Date:

AIM:

To write a Python program to handle exceptions when a number is divided by zero

ALGORITHM:

Step 1: Start
Step 2: Get the numerator from the user
Step 3: Get the denominator from the user
Step 4: Divide the numerator by the denominator using a try catch block
Step 5: If the denominator is non-zero, display the result to the user
Step 6: If the denominator is zero, catch the exception and print the message
Step 7: Stop

PROGRAM:

numerator = int(input ("Enter the numerator : "))


denominator = int(input ("Enter the denominator : "))

try:
result = numerator / denominator
print ("The result is : ", result)
except ZeroDivisionError as e:
print ("Exception Caught : ", e)

79
OUTPUT:

Enter the numerator : 100


Enter the denominator : 5
The result is : 20.0

Enter the numerator : 100


Enter the denominator : 0
Exception Caught : division by zero

RESULT:

The Python program to handle exceptions when a number is divided by zero was successfully
executed.

80
10b. IMPLEMENTING EXCEPTION HANDLING – VOTER AGE VALIDATION

Date:

AIM:

To write a Python program to validate the age of a voter using exception handling

ALGORITHM:

Step 1: Start
Step 2: Get the age of the voter
Step 3: Using a try catch block, check if the age is less than 18 and if true, raise an
exception
Step 4: Catch the raised exception and print the output that the voter is not eligible
Step 5: If age > 18, print that the voter is eligible to vote
Step 6: Stop

PROGRAM:

age = int(input("Enter the age of the candidate : "))

try:
if (age < 18):
raise ValueError()
except ValueError:
print("You must be 18 years or more to vote!")
else:
print("You are eligible to vote")

81
OUTPUT:

Enter the age of the candidate : 25


You are eligible to vote

Enter the age of the candidate : 12


You must be 18 years or more to vote!

RESULT:

The Python program to validate the age of a voter using exception handling was successfully
executed.

82
10c. IMPLEMENTING EXCEPTION HANDLING – STUDENT MARK RANGE
VALIDATION

Date:

AIM:

To write a Python program to validate the subject marks of a student using exception
handling

ALGORITHM:

Step 1: Start
Step 2: Get 3 subject marks of the student
Step 3: Using a try catch block, check if the marks are within the range 0 t0 100
Step 4: If the marks are out of range, raise an exception.
Step 5: Catch the raised exception and print that the marks are out of range
Step 6: Else, print the subject marks of each subject
Step 7: Stop

PROGRAM:

mark1 = int(input("Enter the subject1 mark : "))


mark2 = int(input("Enter the subject2 mark : "))
mark3 = int(input("Enter the subject3 mark : "))

marks = []

marks.append(mark1)
marks.append(mark2)
marks.append(mark3)

83
for count, mark in enumerate(marks):

try:
if (mark < 0 or mark > 100):
raise ValueError()
except ValueError:
print("Your Subject" , count+1, "marks must be in the range 0 - 100")
else:
print("Your Subject" , count+1, "mark is : ", mark)

OUTPUT:

Enter the subject1 mark : 85


Enter the subject2 mark : -12
Enter the subject3 mark : 150

Your Subject 1 mark is : 85


Your Subject 2 marks must be in the range 0 - 100
Your Subject 3 marks must be in the range 0 - 100

RESULT:

The Python program to validate the subject marks of a student using exception handling was
successfully executed.

84
11. EXPLORING THE PYGAME TOOL

Date:

AIM:

To write a Python program to create a basic Pygame window

INTRODUCTION:

Pygame is a cross-platform set of Python modules which is used to create video games. It consists
of computer graphics and sound libraries designed to be used with the Python programming
language.

import pygame - This provides access to the pygame framework and imports all functions of pygame.

pygame.init() - This is used to initialize all the required module of the pygame.

pygame.display.set_mode((width, height)) - This is used to display a window of the desired size.


The return value is a Surface object which is the object where we will perform graphical operations.

pygame.event.get()- This is used to empty the event queue. If we do not call this, the window
messages will start to pile up and, the game will become unresponsive in the opinion of the operating
system.

pygame.QUIT - This is used to terminate the event when we click on the close button at the corner
of the window.

pygame.display.flip() - Pygame is double-buffered, so this shifts the buffers. It is essential to call


this function in order to make any updates that you make on the game screen to make visible.

85
ALGORITHM:

Step 1: Start
Step 2: Import the pygame library
Step 3: Initialize the pygame module
Step 4: Set the screen size
Step 5: Loop till events are received
Step 6: If the event type is Quit, exit the window
Step 7: Display the pygame window
Step 8: Stop

PROGRAM:

import pygame

pygame.init()
screen = pygame.display.set_mode((400,500))
done = False

while not done:


for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pygame.display.flip()

86
OUTPUT:

RESULT:

The Python program to create a basic Pygame window was successfully executed.

87
12a. IMPLEMENTING BOUNCING BALL ANIMATION USING PYGAME

Date:

AIM:

To write a Python program to implement a bouncing ball animation using py game

ALGORITHM:

Step 1: Start
Step 2: Import and initialize the Pygame library
Step 3: Set the drawing mode and the window size as appropriate
Step 4: Set the speed of the moving ball in x & y co-ordinates
Step 5: Load the image of the ball, which needs to be animated
Step 6: Set the rectangular boundaries inside which the ball needs to be moved
Step 7: Move the ball with the assigned speed till it hits any boundary edge
Step 8: If the ball collides with any of the four edges, then change the direction of the ball
Step 9: Update the display
Step 10: Continue the animation till the user quits the program
Step 11: Stop

PROGRAM:

import sys, pygame


pygame.init()

size = width, height = 640, 420


speed = [1, 1]
black = 0, 0, 0

screen = pygame.display.set_mode(size)

88
ball = pygame.image.load("ball.png")
ballrect = ball.get_rect()

while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()

ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]

if ballrect.top < 0 or ballrect.bottom > height:


speed[1] = -speed[1]

screen.fill(black)
screen.blit(ball, ballrect)
pygame.display.flip()

89
OUTPUT:

RESULT:

The Python program to implement a bouncing ball animation using pygame was successfully
executed.

90
12b. IMPLEMENTING CAR RACING GAME USING PYGAME

Date:

AIM:

To write a Python program to implement a car racing game using pygame

ALGORITHM:

Step 1: Start
Step 2: Initialize the pygame modules
Step 3: Load the game assets
Step 4: Map the left and right keys to the user car
Step 5: Generate and move police cars at random and move it from top towards the user
car
Step 6: Evade the user car from colliding with the oncoming cars
Step 7: If a collision is detected, end the game
Step 8: Stop

PROGRAM:

#import pygame package


import pygame
#import the time package to restart the game
import time

#import for the random library to randomize the car coming from the opposite
side.
import random

#initiate package
pygame.init()

91
#color code in RGB form
gray=(60,60,60)
#color code in RGB form
black=(255,0,0)
#set width & height of the display
display=pygame.display.set_mode((830,600))
#set name of the game window
pygame.display.set_caption("Car Racing Game")

#load car image


carimg=pygame.image.load("Ex 12/Car Game/car1.png")
#load background image for the left side
backgroundleft=pygame.image.load("Ex 12/Car Game/left.png")
#load background image for the right side
backgroundright=pygame.image.load("Ex 12/Car Game/right.png")
#Defined car width
car_width=23

#define police car functions that are coming from the opposite side.
def policecar(police_startx,police_starty,police):
if police==0:
#for police car no 2
police_come=pygame.image.load("Ex 12/Car Game/car2.png")
if police==1:
#for police car no 3
police_come=pygame.image.load("Ex 12/Car Game/car3.png")
if police==2:
#for police car no 1

police_come=pygame.image.load("Ex 12/Car Game/car1.png")


#display the police car
display.blit(police_come,(police_startx,police_starty))

92
def background():
#defining the position of background image for left side in x axis & y
axis
display.blit(backgroundleft,(0,0))

#defining the position of background image for right side in x axis & y
axis
display.blit(backgroundright,(700,0))

#creating the function that will display the game over message
def crash():
message_display("Game Over")

#create function for customizing the game over message


def message_display(text):
#set font style and size of the message
large_text=pygame.font.Font("Ex 12/Car Game/freesansbold.ttf",80)
#set function to edit the message
textsurf,textrect=text_object(text,large_text)
#set the position of the message on the screen
textrect.center=((400),(300))
#display the message
display.blit(textsurf,textrect)
pygame.display.update()
#After the car has crashed, wait 3 seconds.
time.sleep(3)
#call the loop function to restart the game
loop()

#This function will display the message after the car has crashed.
def text_object(text,font):
#set color of the message
text_surface=font.render(text,True,black)
#after that restart the game & ready to give some input

93
return text_surface,text_surface.get_rect()

#create car function


def car(x,y):
#set position of the car
display.blit(carimg,(x,y))

#all the function are called using this function


def loop():
#set car position for x and y axis
x=400
y=540
#set changing position of the car
x_change=0
y_change=0
#set police car speed
policecar_speed=9
#set starting stage for the police car
police=0
#with this police car will come randomly
police_startx=random.randrange(130,(700-car_width))
#police car will comes in y axis in negative value because car is coming
from opposite side
police_starty=-600
# set police car height and width
police_width=23
police_height=47

#if the game doesn't have any problem to start


bumped=False
#start the game
while not bumped:

94
#defining the input of the game
for event in pygame.event.get():
#if quit input is given

if event.type==pygame.QUIT:
# bumped=True #game will stop
pygame.quit()
quit()

#defining the arrow keys


if event.type==pygame.KEYDOWN:
#if user is pressing the left arrow
if event.key==pygame.K_LEFT:
#car will move left side -1
x_change=-1
#if user is pressing the right arrow
if event.key==pygame.K_RIGHT:
#car will move left side 1
x_change=1
#if any key is not being pressed then stop the car
if event.type==pygame.KEYUP:
x_change=0
x+=x_change

#setting the color of the road


display.fill(gray)
#car speed that are coming from opposite side(y axis)
background()
police_starty-=(policecar_speed/1.2)
policecar(police_startx,police_starty,police)
#police car speed will increase slowly
police_starty+=policecar_speed
car(x,y)

95
#if the car goes out of range(side wall of the road)
if x<130 or x>700-car_width:
#bumped=True #game is over
#call crash function
crash()

#seting how far the police car will go


if police_starty>600:
#only one car will cross the road in one time
police_starty=0-police_height
#then other car will come
police_startx=random.randrange(130,(1000-300))
#set how many car will come
police=random.randrange(0,2)

#if the police car does not cross the road then crash the car
if y<police_starty+police_height:
if x > police_startx and x < police_startx + police_width or x +
car_width > police_startx and x + car_width < police_startx +
police_width :
crash()

#restart the game


pygame.display.update()
loop() # exiting from game
pygame.quit()
quit()

96
OUTPUT:

RESULT:

The Python program to implement a car racing game using pygame was successfully
executed.

97
98

You might also like