0% found this document useful (0 votes)
16 views95 pages

Python Flowcharts for Various Calculations

The document outlines various Python programming exercises including flowcharts for electricity billing, retail shop billing, and calculating sin series. It also includes algorithms for swapping variables, circulating values, calculating distances, and generating Fibonacci series, along with their respective outputs. Each exercise concludes with a verification statement confirming successful execution.

Uploaded by

narumugam27
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)
16 views95 pages

Python Flowcharts for Various Calculations

The document outlines various Python programming exercises including flowcharts for electricity billing, retail shop billing, and calculating sin series. It also includes algorithms for swapping variables, circulating values, calculating distances, and generating Fibonacci series, along with their respective outputs. Each exercise concludes with a verification statement confirming successful execution.

Uploaded by

narumugam27
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

IDENTIFICATION AND SOLVING OF SIMPLE REAL LIFE OR

SCIENTIFIC OR TECHNICAL PROBLEMS, AND DEVELOPING


[Link](A)
DATE: FLOW CHARTS FOR THE SAME.
ELECTRICITY BILLING

AIM:

To construct a flowchart for electricity bill in python.

ALGORITHM:

Step 1: Start
Step 2: Input unit consumed by customer
Step 3: If unit consumed less or equal to 200 units. Then Total_charge = [Link] * 2.50
step4: If unit consumed more than 201 units but less than 500 units. Then add the first
200 unit’s amount i.e. 2.50. Which is given by Total_charge= ([Link] 200)*3.50 + (200 *
2.50).
Step 5: If unit consumed more than 501units. Then add first two units 200 and 500units
amount i.e. 2.50& 3.50. Which is given by Total_charge= ([Link]- 0) * 5.00 + (300 *
3.50) + (200*2.50).
Step 6: Similarly check rest of the conditions and calculate total amount.
Step 7: After calculating total amount print the statement in Total charge.
Step 8: Stop.

FromUnit ToUnit Rate(Rs.) [Link]


1 100 0 100
101 200 2 200
201 500 3 500-
- 101-200 3.5 >500
201-500 4.6 >500
>500 606 >500
FLOWCHART:

RESULT:

Thus the flowchart for electricity bill was successfully verified.


[Link](B) RETAIL SHOP BILLING
DATE:

AIM:

To construct a flowchart for retail shop billing in python.

ALGORITHM:

Step 1: Start.
Step 2: Open the APP.
Step 3: Initialize or select the packages/items.
Step 4: Add product details.(insert/delete/update).
Step 5: Scan barcode.
Step 6: Check shopping.
Step 7: Calculate total, update database and give feedback.
Step 8: Make payment.
Step 9: Stop.
FLOWCHART:

RESULT:

Thus the flowchart for retail shop billing was successfully verified.
[Link](C) SIN SERIES
DATE:

AIM:

To construct a flowchart for calculating sin series in python.

ALGORITHM:

Step 1: Start.
Step 2: Take a value of x in degrees & the number of terms that store it in separate
variables.
Step 3: Pass these values to the sine function as argument.
Step 4: Define a sine function and using a for loop .
Step 5: First convert degree to radius.
Step 6: Then use the sine formula expansion and add each term to the sun variable.
Step 7: Print the final sum of the expression.
Step 8: Make payment.
Step 9: Stop.
FLOWCHART:

RESULT:

Thus the flowchart for calculating sin series was successfully verified.
[Link](D) WEIGHT OF A STEEL BAR
DATE:

AIM:

To construct a flowchart for calculating weight of a steel bar in python.

ALGORITHM:

Step 1: Start.
Step 2: Initialize the variable.
Step 3: Read the values for the density and volume of the steel bar.
Step 4: Calculate the weight using the formula weight=volume*density
Step 5: Print the values.
Step 6: Stop.
FLOWCHART:

RESULT:

Thus the flowchart for calculating weight of a steel bar was successfully verified.
COMPUTE ELECTRICAL CURRENT IN THREE PHASE AC
[Link](E)
DATE: CIRCUIT

AIM:

To construct a flowchart for computing electrical current in three phase AC circuit in


python.

ALGORITHM:

Step 1: Start.
Step 2: Generation of 3-Phase EMF in AC Circuits
Step 3: Phase Sequence in Three-Phase AC Circuits
Step 4: Conversion of Balanced Load System from Star to Delta and Vice-Versa
Step 5: Balancing Parallel Loads in 3 Phase AC Circuit
Step 6: Stop.
FLOWCHART:

RESULT:
Thus the flowchart for computing electrical current in three phase AC circuit was
successfully verified.
[Link](A)
EXCHANGE OF THE VALUES OF TWO VARIABLES
DATE:

AIM:
To write a Python program to perform Swapping of two numbers.

ALGORITHM:

Step 1: Start
Step 2: Define a function swap and call the function.
Step 3: Get the first number
Step 4: Get the second number
Step 5: Print the numbers before swapping
Step 6: Assign the first number with temporary variable ‘temp’
Step 7: Store the second number to the first number
Step 8: Reassign the second number to the temporary variable
Step 9: Print the Swapped values.
Step 10: Stop
PROGRAM:

Method-1-without using another variable

x=input("enter the first number:")


y=input("enter the second number:")
z=input("enter the third number:")
print("Numbers before swapping:",x,y,z)
x,y,z=z,y,x
print("Numbers after swapping:",x,y,z)
OUTPUT
enter the first number:10
enter the second number:15
enter the third number:20
Numbers before swapping: 10 15 20
Numbers after swapping: 20 15 10

Method-II-with using Third variable

x=input("Enter the First number:")


y=input("Enter the Second number:")
print("Numbers before swapping:",x,y)
temp=x
x=y
y=temp
print("Numbers after swapping:",x,y)

OUTPUT
Enter the First number:10
Enter the Second number:15
Numbers before swapping: 10 15
Numbers after swapping: 15 10
Method-III- Using Function Concept

def swap():
a= int(input("Enter the First number:"))
b=int(input("Enter the Second number:"))
print("The numbers before swapping",a,b)
temp=a
a=b
b=temp
print("The numbers after swapping",a,b)
swap()

OUTPUT
Enter the First number:10
Enter the Second number:15
The numbers before swapping 10 15
The numbers after swapping 15 10

RESULT:
Thus the Python programs to exchange the values between two variables are executed and
verified successfully.
[Link](B)
CIRCULATE THE VALUES OF N VARIABLES
DATE:

AIM:
To write a python program to circulate ‘n’ Variables

ALGORITHM:

Step 1: Start
Step 2: Circulate the values of ‘n’ variables
Step 3: Get the input from the user
Step 4: To create the empty list then declare the conditional statement using for loop
Step 5: Use append operation to add element in the list and rotate the values
Step 6: Stop
PROGRAM:
n = int(input("Enter number of values : "))
list1 = []
for val in range(0,n):
ele = int(input("Enter integer : "))
[Link](ele)
print("Circulating the elements of list ", list1)
for val in range(0,n):
ele = [Link](0)
[Link](ele)
print(list1)

OUTPUT
Enter number of values : 3
Enter integer : 1
Enter integer : 2
Enter integer : 3
Circulating the elements of list [1, 2, 3]
[2, 3, 1]
[3, 1, 2]
[1, 2, 3]

RESULT:
Thus the Python programs to circulate the N Values are executed and verified successfully..
[Link](C)
CALCULATE THE DISTANCE BETWEEN TWO POINTS
DATE:

AIM:
To write a Python program to find the Distance between Two Points

ALGORITHM:

Step 1: Start
Step 2: Import the module ‘math’
Step 3: Define a function distance with four coordinates and call the function.
Step 4: Calculate the difference of the ‘x’ coordinates as ‘a’.
Step 5: Calculate the difference of the ‘y’ coordinates as ‘b’
Step 6: Calculate the sum of ‘x’ and ‘y’ coordinates c= (a**2) + (b**2)
Step 7: Calculate the square root of ‘c’
Step 8: Print the distance between two points.
Step 9: Stop.
PROGRAM:
Method-1

import math
x1=int(input("Enter x1:"))
y1=int(input("Enter y1:"))
x2=int(input("Enter x2:"))
y2=int(input("Enter y2:"))
distance=[Link](((x2-x1)**2)+((y2-y1)**2))
print("Distance=",distance)
OUTPUT
Enter x1:5
Enter y1:4
Enter x2:6
Enter y2:5
Distance= 1.4142135623730951

Method-2

import math
def distance(x1,y1,x2,y2):
a=x2-x1
b=y2-y1
c=(a**2)+(b**2)
d=[Link](c)
return d
a=int(input("Enter x1:"))
b=int(input("Enter y1:"))
c=int(input("Enter x2:"))
d=int(input("Enter y2:"))
e=distance(a,b,c,d)
print("The distance between two points is ",e)
OUTPUT
Enter x1:5
Enter y1:4
Enter x2:6
Enter y2:5
The distance between two points is 1.4142135623730951

RESULT:
Thus the Python programs to distance between two points are executed and verified
successfully.
SCIENTIFIC PROBLEMS USING CONDITIONALS AND ITERATIVE
[Link](A)
LOOPS
DATE:
NUMBER SERIES

AIM:
To write a Python program to evaluate the Fibonacci series for n terms.

ALGORITHM:

Step 1: Start
Step 2: Initialize the value of x=0
Step 3: Initialize the value of y =1
Step 4: Read the value of n
Step 5: For I in range of n+1
z=x+y
Print x
x=y
y =z
Step 6: End of the program.
Step 7: Stop.
PROGRAM:
Method-1: Simple Iteration

num = int(input("Enter the number of terms:"))


n1, n2 = 0, 1
print("Fibonacci Series:", n1, n2, end=" ")
for i in range(2, num):
n3 = n1 + n2
n1 = n2
n2 = n3
print(n3, end=" ")
print()
OUTPUT
Enter the number of terms: 10
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34

Method-2: using recursive function

def fibonacciSeries(i):
if i <= 1:
return i
else:
return (fibonacciSeries(i - 1) + fibonacciSeries(i - 2))
num = int(input("Enter the number of terms:"))
if num <=0:
print("Please enter a Positive Number")
else:
print("Fibonacci Series:", end=" ")
for i in range(num):
print(fibonacciSeries(i), end=" ")
OUTPUT
Enter the number of terms:15
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Method-3: using formula

import math
def fibonacciSeries(phi, n):
for i in range(0, n + 1):
RESULT: = round(pow(phi, i) / [Link](5))
print(RESULT:, end=" ")
num = int(input("Enter the number of terms:"))
phi = (1 + [Link](5)) / 2
fibonacciSeries(phi, num)

OUTPUT
Enter the number of terms: 5
011235

RESULT:
Thus the python program to evaluate the Fibonacci series for n terms is executed and
verified successfully.
[Link](B)
NUMBER PATTERN
DATE:

AIM:
To write a python program to construct number pattern.

ALGORITHM:

Step 1: Start.
Step 2: Declare the values for rows.
Step 3: Let i and j be an integer number
Step 4: Repeat step 5 to 8 until all values parsed
Step 5: Set i in outer loop using range function, i=rows+1 and rows will be initialized to i
Step 6: Set j in inner loop using range function and i integer will be initialized to j
Step 7: Print i until condition becomes false in inner loop.
Step 8: Print new line until condition becomes false in outer loop.
Step 9: Stop.
PROGRAM:
n = int(input("Enter the Number to form a pattern: "))
for i in range(n+1):
for j in range(1, i+1):
print(j, end=' ')
print()

OUTPUT
Enter the Number to form a pattern: 10

1
12
123
1234
12345
123456
1234567
12345678
123456789
1 2 3 4 5 6 7 8 9 10

RESULT:

Thus the Python program to evaluate number pattern is executed and verified successfully.
[Link](C)
PYRAMID PATTERN
DATE:

AIM:
To write a python program to construct number pattern.

ALGORITHM:

Step 1: Start.
Step 2: Declare the values for rows.
Step 3: Let i and j be an integer number
Step 4: Repeat step 5 to 8 until all values parsed
Step 5: Set i in outer loop using range function, i=rows+1 and rows will be initialized to i
Step 6: Set j in inner loop using range function and i integer will be initialized to j
Step 7: Print i until condition becomes false in inner loop.
Step 8: Print new line until condition becomes false in outer loop.
Step 9: Stop.
PROGRAM:
n = int(input("Enter the number to form pattern:"))
for i in range(n):
for j in range(n - i - 1):
print(' ', end=' ')
for k in range(2 * i + 1):
print(k + 1, end=' ')
print()

OUTPUT
Enter the number to form pattern: 5
1
123
12345
1234567
123456789

RESULT:

Thus the Python program to evaluate pyramid pattern is executed and verified successfully.
[Link](A) IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS USING
DATE: LISTS, TUPLES
ITEMS PRESENT IN A LIBRARY

AIM:
To write a python program to implement items present in library.

ALGORITHM:

Step 1: Start.
Step 2: Create the variables inside the variable assigned the list of elements based on the
library using list and tuple.
Step 3: Using array index to print the items using list and tuple.
Step 4: Print the result using output statement.
Step 5: Stop.
PROGRAM:
Method-1: LIST

print ("Welcome to Riya Advanced Library")


n = int(input("Enter number of books to be inserted: "))
Library=[]
for val in range(0,n):
ele = input("Enter the book name : ")
[Link](ele)
print(" The list in the library:",Library)
[Link](ele)
print(Library)
[Link](1)
print(Library)
[Link]("CD’s")
print(Library)
[Link](1,"DVD's")
print(Library)
print([Link]("DVD's"))
del Library[1]
print(Library)
[Link]()
print(Library)

OUTPUT
Welcome to Riya Advanced Library
Enter number of books to be inserted: 3
Enter the book name : C
Enter the book name : C++
Enter the book name : JAVA
The list in the library: ['C', 'C++', 'JAVA']
['C', 'C++']
['C']
['C', 'CD’s']
['C', "DVD's", 'CD’s']
1
['C', 'CD’s']
[]
Method-2: TUPLES

tup1= (12134,250000)
tup2= ('books','totalprice')
#tup1[0]=100 ---------- Not assigned in tuple
#Solet's create a new tuple as follow stup3
tup3=tup1+tup2;
print(tup3)

OUTPUT
(12134, 250000, 'books', 'totalprice')

RESULT:

Thus the Python program to implement items present in the library is executed and verified
successfully.
[Link](B)
DATE: COMPONENTS OF A CAR

AIM:
To write a python program to implement components of a car.

ALGORITHM:

Step 1: Start.
Step 2: Create the variables inside the 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: Print the result using output statement.
Step 5: Stop.
PROGRAM:
Method-1: LIST

cars = ["Nissan", "Mercedes Benz", "Ferrari", "Maserati", "Jeep", "Maruti Suzuki"]


new_list=[]
for i in cars:
if"M"in i:
new_list.append(i)
print(new_list)

OUTPUT
['Mercedes Benz']
['Mercedes Benz', 'Maserati']
['Mercedes Benz', 'Maserati', 'Maruti Suzuki']

Method-2: TUPLES

carparts=('Engine', 'Transmission', 'Wheel', 'Gear', 'Brake', 'Battery')


print('Our tuple is: ',carparts)
print('Item in the first position is: ',carparts[0])
print('Item in the 5th position is: ',carparts[4])
indexOfWheel=[Link]('Wheel')
print('Index of Wheel is: ', indexOfWheel)
lengthcarpartsTuple = len(carparts)
print('Length of the carparts tuple is: ',lengthcarpartsTuple)
for item in carparts:
print(item)
print(carparts*2)
print(carparts[1:4])
if "Brake" in carparts:
print("Brake is available in the carparts tuple")
else:
print("Brake is not available tuple in the carparts")

OUTPUT
Our tuple is: ('Engine', 'Transmission', 'Wheel', 'Gear', 'Brake', 'Battery')
Item in the first position is: Engine
Item in the 5th position is: Brake
Index of Wheel is: 2
Length of the carparts tuple is: 6
Engine
Transmission
Wheel
Gear
Brake
Battery
('Engine', 'Transmission', 'Wheel', 'Gear', 'Brake', 'Battery', 'Engine', 'Transmission', 'Wheel',
'Gear', 'Brake', 'Battery')
('Transmission', 'Wheel', 'Gear')
Brake is available in the carparts tuple

RESULT:

Thus the Python program to implement components of a car is executed and verified
successfully.
[Link](C)
DATE: CONSTRUCTION OF A BUILDING

AIM:
To write a python program to implement materials required for the construction of a
building.

ALGORITHM:

Step 1: Start.
Step 2: Create the variables and stored the unordered list of elements based on the
materials required for the construction of a building using list and tuple.
Step 3: Using array index to print the items using list and tuple.
Step 4: Print the result using output statement.
Step 5: Stop.
PROGRAM:
Method-1: LIST

materials_list = ["cement", "steal", "sand", "coarse aggregate", "bricks", "water"]


def main():
global materials_list
print("\n1. Find Position")
print("2. Slice materials")
print("3. Add material")
print("4. Repeat materials")
print("5. Update materials")
print("6. Checking presence of a material")
print("7. Compare material")
print("8. Display materials")
print("9. Exit")
choice = int(input("Enter an integer option : "))
if choice == 1:
position = int(input("Enter position : "))
print(materials_list[position-1]) # // Indexing
main()
elif choice == 2:
starting = int(input("Enter starting position : "))
ending = int(input("Enter ending position : "))
print(materials_list[starting:ending]) # // Slicing
main()

elif choice == 3:
material = input("Enter material name : ")
materials_list = materials_list + [material] # // Concatenation
print("Material added", materials_list)
main()

elif choice == 4:
repeat_n = int(input("Enter number of times to repeat : "))
print(materials_list*repeat_n) # // Repeatation
main()
elif choice == 5:
position = int(input("Enter position to be updated : "))
material = input("Enter the new name of the material : ")
materials_list[position-1] = material # // Updating
print("Material updated", materials_list)
main()
elif choice == 6:
material = input("Enter material name : ")
if material in materials_list: # // Membership operator
print("Material present")
else:
print("Not present")
main()
elif choice == 7:
position = int(input("Enter position of comparison : "))
material = input("Enter material name : ")
if materials_list[position-1] == material: # // Comparison operator
print("Material is same")
else:
print("Materials are not same")
main()
elif choice == 8:
for i in materials_list: # // Iterating through the list
print(i)
main()
elif choice == 9:
print("Thank you for using our application")
return
main()

OUTPUT

1. Find Position
2. Slice materials
3. Add material
4. Repeat materials
5. Update materials
6. Checking presence of a material
7. Compare material
8. Display materials
9. Exit
Enter an integer option : 3
Enter material name : rod
Material added ['cement', 'steal', 'sand', 'coarse aggregate', 'bricks', 'water', 'rod']

1. Find Position
2. Slice materials
3. Add material
4. Repeat materials
5. Update materials
6. Checking presence of a material
7. Compare material
8. Display materials
9. Exit
Enter an integer option : 5
Enter position to be updated : 4
Enter the new name of the material : rings
Material updated ['cement', 'steal', 'sand', 'rings', 'bricks', 'water', 'rod']

1. Find Position
2. Slice materials
3. Add material
4. Repeat materials
5. Update materials
6. Checking presence of a material
7. Compare material
8. Display materials
9. Exit
Enter an integer option : 8
cement
steal
sand
rings
bricks
water
rod

1. Find Position
2. Slice materials
3. Add material
4. Repeat materials
5. Update materials
6. Checking presence of a material
7. Compare material
8. Display materials
9. Exit
Enter an integer option : 9
Thank you for using our application

Method-2:LIST

materialsforconstruction = ["cementbags", "bricks", "sand", "Steelbars", "Paint"]


[Link](" Tiles")
[Link](3,"Aggregates")
[Link]("sand")
materialsforconstruction[5]="electrical"
print(materialsforconstruction)

OUTPUT
['cementbags', 'bricks', 'Aggregates', 'Steelbars', 'Paint', 'electrical']

Method-3: TUPLES

materialsforconstruction = ("cementbags", "bricks", "sand", "Steelbars", "Paint")


print("materialsforconstruction")
#del(materialsforconstruction)
#print ("After deleting materials for construction")
print("materialsforconstruction")
print("materialsforconstruction[0]:",materialsforconstruction[0])
print("materialsforconstruction[1:5]:",materialsforconstruction[1:5])
OUTPUT
materialsforconstruction
materialsforconstruction
materialsforconstruction[0]: cementbags
materialsforconstruction[1:5]: ('bricks', 'sand', 'Steelbars', 'Paint')
RESULT:

Thus the Python program to implement materials for construction of a building is executed
and verified successfully.
IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS
[Link](A) USING SETS, DICTIONARIES
DATE:
LANGUAGE

AIM:
To write a python program to implement components of language using sets and
dictionaries.

ALGORITHM:

Step 1: Start.
Step 2: Create the variables and stored the unordered list of elements based on the
components of language using sets and dictionaries.
Step 3: Using array index to print the items using sets and dictionaries.
Step 4: Print the RESULT: using output statement.
Step 5: Stop.
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 {'Syllabus', 'Sentences', 'Pitch', 'Grammar', 'Words', 'Script', 'Phonetics',
'Context'}
Intersection of L1 and L2 is {'Syllabus', 'Grammar'}
Difference of L1 and L2 is {'Pitch', 'Sentences', 'Script'}
Symmetric difference of L1 and L2 is {'Sentences', 'Script', 'Phonetics', 'Pitch', 'Words',
'Context'}

RESULT:

Thus the Python program to implement components of language using sets and
dictionaries is executed and verified successfully.
[Link](B) COMPONENTS OF AN AUTOMOBILE
DATE:

AIM:
To write a python program to implement components of an automobile using sets and
dictionaries.

ALGORITHM:

Step 1: Start.
Step 2: Create the variables and stored the unordered list of elements based on the
components of an automobile using sets and dictionaries.
Step 3: Using array index to print the items using sets and dictionaries.
Step 4: Print the RESULT: using output statement.
Step 5: Stop.
PROGRAM:
auto_comp = set(["Chassis", "Engine", "Transmission System", "Body"])
comp_dict = {}
for i in auto_comp:
comp_dict[i] = 1
while True:
print("1. Add component")
print("2. Delete component")
print("3. Display components")
print("4. Exit")
choice = int(input("Enter an integer option : "))
if choice == 1:
comp_name = input("Component name : ")
if comp_name in comp_dict:
comp_dict[comp_name] += 1
else:
comp_dict[comp_name] = 1
print("Component added successfully.!")
elif choice == 2:
comp_name = input("Component name : ")
if comp_name in comp_dict:
del comp_dict[comp_name]
print("Component deleted successfully.!")
else:
print("Component not found!")
elif choice == 3:
print()
counter = 1
for i in comp_dict:
print(f"{counter}. {i} : {comp_dict[i]}")
counter += 1
elif choice == 4:
print("\nThank you for using our program!")
exit()
else:
print("Please enter a valid choice")
print()

OUTPUT
1. Add component
2. Delete component
3. Display components
4. Exit
Enter an integer option : 1
Component name : Engine

1. Add component
2. Delete component
3. Display components
4. Exit
Enter an integer option : 3
1. Engine : 2
2. Body : 1
3. Transmission System : 1
4. Chassis : 1

1. Add component
2. Delete component
3. Display components
4. Exit
Enter an integer option : 1
Component name : Body

1. Add component
2. Delete component
3. Display components
4. Exit
Enter an integer option : 3
1. Engine : 2
2. Body : 2
3. Transmission System : 1
4. Chassis : 1

1. Add component
2. Delete component
3. Display components
4. Exit
Enter an integer option : 2
Component name : Chassis
Component deleted successfully.!

1. Add component
2. Delete component
3. Display components
4. Exit
Enter an integer option : 3
1. Engine : 2
2. Body : 2
3. Transmission System : 1

1. Add component
2. Delete component
3. Display components
4. Exit
Enter an integer option : 4
Thank you for using our program!

RESULT:

Thus the Python program to implement components of an automobile using sets and
dictionaries is executed and verified successfully.
[Link](C)
DATE:
ELEMENTS OF A CIVIL STRUCTURE

AIM:
To write a python program to implement elements of a civil structure using sets and
dictionaries.

ALGORITHM:

Step 1: Start.
Step 2: Create the variables and stored the unordered list of elements of a civil structure
using sets and dictionaries.
Step 3: Using array index to print the items using sets and dictionaries.
Step 4: Print the RESULT: using output statement.
Step 5: Stop.
PROGRAM:
civil_elements = set(["Water", "Sand", "Cement", "Coarse aggregate", "Steel"])
civil_elem_dict = {}
for i in civil_elements:
civil_elem_dict[i] = 1
print("Civil Structures\n")
while True:
print("1. Add element")
print("2. Delete element")
print("3. Display element")
print("4. Exit")
choice = int(input("Enter an integer option : "))
if choice == 1:
element_name = input("Element name : ")
if element_name in civil_elem_dict:
civil_elem_dict[element_name] += 1
else:
civil_elem_dict[element_name] = 1
print("Element added successfully.!")
elif choice == 2:
element_name = input("Element name : ")
if element_name in civil_elem_dict:
del civil_elem_dict[element_name]
print("Element deleted successfully.!")
else:
print("Element not found!")
elif choice == 3:
print()
counter = 1
for i in civil_elem_dict:
print(f"{counter}. {i} : {civil_elem_dict[i]}")
counter += 1
elif choice == 4:
print("\nThank you for using our program!")
exit()
else:
print("Please enter a valid choice")
print()

OUTPUT
Civil Structures

1. Add element
2. Delete element
3. Display element
4. Exit
Enter an integer option : 1
Element name : Sand

1. Add element
2. Delete element
3. Display element
4. Exit
Enter an integer option : 3

1. Steel : 1
2. Sand : 2
3. Water : 1
4. Cement : 1
5. Coarse aggregate : 1

1. Add element
2. Delete element
3. Display element
4. Exit
Enter an integer option : 2
Element name : Steel
Element deleted successfully.!

1. Add element
2. Delete element
3. Display element
4. Exit
Enter an integer option : 3

1. Sand : 2
2. Water : 1
3. Cement : 1
4. Coarse aggregate : 1

1. Add element
2. Delete element
3. Display element
4. Exit
Enter an integer option : 4

Thank you for using our program!

RESULT:

Thus the Python program to implement elements of a civil structure using sets and
dictionaries is executed and verified successfully.
[Link](A) IMPLEMENTING PROGRAMS USING FUNCTIONS.
DATE: FACTORIAL

AIM:
To write a python program to calculate the factorial of a number.

ALGORITHM:

Step 1: Start.
Step 2: Get the positive integer input (n) from user.
Step 3: Check the values of n equal to 0 or not.
Step 4: If it is 0 it will return i otherwise else statement will be executed.
Step 5: using the formula, calculate the factorial of a number.
Step 6: Print the RESULT: using output statement.
Step 7: Stop.
PROGRAM:
# factorial of given number
def factorial(n):
if n== 0:
return 1
else:
return n*factorial(n-1)
n=int(input("Input a number to compute the factiorial : "))
print(factorial(n))

OUTPUT
Input a number to compute the factiorial : 6
720

RESULT:

Thus the python program to calculate the factorial of a number is executed and verified
successfully.
[Link](B)
DATE:
LARGEST OF TWO NUMBER IN A LIST

AIM:
To write a python program to get the largest number from the list.

ALGORITHM:

Step 1: Start.
Step 2: Declare a function that will find a largest number.
Step 3: Use max() and store the value returned by it in a variable.
Step 4: Return the variable.
Step 5: Declare and initialize the list
Step 6: Call the function and Print the value returned by it.
Step 7: Stop.
PROGRAM:
Method-1:

n=int(input("Enter the list size:"))


a=[]
for i in range(n):
num=int(input("Enter the number"))
[Link](num)
print (a)
max=a[0]
for i in range(n):
if(max<a[i]):
max=a[i]
print ("maximum",max)

OUTPUT
Enter the list size:2
Enter the number25
[25]
Enter the number30
[25, 30]
maximum 30

Method-2:

mylist=[20,100,30,1,10]
[Link]()
print(mylist)
print("1st largest element is:", mylist[-1])
print("2nd largest element is:", mylist[-2])
OUTPUT
[1, 10, 20, 30, 100]
1st largest element is: 100
2nd largest element is: 30
RESULT:

Thus python program to get the largest number from the list is executed and verified
successfully.
[Link](C)
DATE:
AREA OF SHAPE

AIM:
To write a python program to implement area of shape using function.

ALGORITHM:

Step 1: Start.
Step 2: Initialize the math and Variables.
Step 3: Read the value
Step4: Define and call function for particular area.
Step 5: Apply it in the formula.
Step 6: Display the result
Step 7: Stop.
PROGRAM:
# define a function for calculating
# the area of a shapes
def calculate_area(name):
# converting all characters into lower cases
name = [Link]()
# check for the conditions
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(f"The area of rectangle is {rect_area}.")
elif name == "square":
s = int(input("Enter square's side length: "))
# calculate area of square
sqt_area = s * s
print(f"The area of square is {sqt_area}.")
elif name == "triangle":
h = int(input("Enter triangle's height length: "))
b = int(input("Enter triangle's breadth length: "))
# calculate area of triangle
tri_area = 0.5 * b * h
print(f"The area of triangle is {tri_area}.")
elif name == "circle":
r = int(input("Enter circle's radius length: "))
pi = 3.14
# calculate area of circle
circ_area = pi * r * r
print(f"The area of triangle is {circ_area}.")
elif name == 'parallelogram':
b = int(input("Enter parallelogram's base length: "))
h = int(input("Enter parallelogram's height length: "))
# calculate area of parallelogram
para_area = b * h
print("The area of parallelogram is {para_area}.")

else:
print("Sorry! This shape is not available")
# driver code
if __name__ == "__main__" :
print("Calculate Shape Area")
shape_name = input("Enter the name of shape whose area you want to find: ")
# function calling
calculate_area(shape_name)

OUTPUT
Enter the name of shape whose area you want to find: rectangle
Enter rectangle's length: 5
Enter rectangle's breadth: 5
The area of rectangle is 25.
Calculate Shape Area

RESULT:

Thus python program to implement area of shape using function is executed and verified
successfully.
[Link](A) IMPLEMENTING PROGRAMS USING STRINGS
DATE: REVERSE A STRING

AIM:
To write a python program to implement reverse a string.

ALGORITHM:

Step 1: Start.
Step 2: Read the string from user.
Step 3: Calculate the length of the string.
Step 4: Initialize rev = " "[empty string] .
Step 5: Initialize = length-1
Step 6: Repeat until i>=0.
Step 7: rev=rev+character atb position "i" of the string.
Step 8: i= i-1
Step 9: print rev
Step 10: Stop.
PROGRAM:
def reverse(string):
string = "".join(reversed(string))
return string
s = input("Enter any string: ")
print ("The original string is : ",end="")
print (s)
print ("The reversed string(using reversed) is : ",end="")
print (reverse(s))

OUTPUT
Enter any string: MAMAEARTH
The original string is : MAMAEARTH
The reversed string(using reversed) is : HTRAEAMAM

RESULT:

Thus python program to implement reverse a string is executed and verified successfully..
[Link](B)
DATE:
PALINDROME

AIM:
To write a python program to implement palindrome.

ALGORITHM:

Step 1: Start.
Step 2: Read the string from user.
Step 3: To get the reverse of the string use the slice operator.
Step 4: If the reversed string matches the original string then it is a palindrome else it is
not a palindrome.
Step 5: Stop.
PROGRAM:
string=input(("Enter a string:"))
if(string==string[::-1]):
print("The string is a palindrome")
else:
print("Not a palindrome")

OUTPUT
Enter a string:MADAM
The string is a palindrome
Enter a string:MOTHER
Not a palindrome

RESULT:

Thus python program to implement palindrome is executed and verified successfully.


[Link](C)
DATE:
CHARACTER COUNT

AIM:
To write a python program to implement character count.

ALGORITHM:

Step 1: Start.
Step 2: Read the string from user.
Step 3: Enter the character to count from the string.
Step 4: Use [Link](char) to count the given character and display the RESULT:.
Step 5: Stop.
PROGRAM:
string = input("Enter any string: ")
char = input("Enter a character to count: ")
val = [Link](char)
print(val,"\n")

OUTPUT
Enter any string: HELLO WORLD
Enter a character to count: O
2

RESULT:

Thus python program to implement character count is executed and verified successfully.
[Link](D)
DATE:
REPLACING CHARACTER

AIM:
To write a python program to implement replacing character using string function.

ALGORITHM:

Step 1: Start.
Step 2: Get the string from user.
Step 3: Get the string to be replaced with new one.
Step 4: Use [Link]() ,replace with the new string and display the RESULT:.
Step 5: Stop.
PROGRAM:
string = input("Enter any string: ")
str1 = input("Enter old string: ")
str2 = input("Enter new string: ")
print([Link](str1, str2))

OUTPUT
Enter any string: PYTHON PROGRAMMING
Enter old string: PYTHON
Enter new string: C
C PROGRAMMING

RESULT:

Thus python program to implement replacing character using string function is executed
and verified successfully.
IMPLEMENTING PROGRAMS USING WRITTEN MODULES
[Link](A) AND PYTHON STANDARD LIBRARIES
DATE:
PANDAS

AIM:
To write a python program to compare the elements of two panda series using pandas
library.
Sample Series: [2, 4, 6, 8, 10], [1, 3, 5, 7, 10]

ALGORITHM:

Step 1: Start.
Step 2: Get the two different array of string from user.
Step 3: To compare two set of array for equal, greater than and less than
Step 4: Using the mathematical calculation do the comparisons.
Step 5: Display the output.
Step 6: Stop
PROGRAM:
import pandas as pd
ds1 = [Link]([2, 4, 6, 8, 10])
ds2 = [Link]([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)

OUTPUT

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

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

RESULT:

Thus python program to compare the elements of two panda series using pandas library is
executed and verified successfully.
[Link](B) NUMPY
DATE:

AIM:
To write a python program to implement numpy module.

ALGORITHM:

Step 1: Start.
Step 2: Get the dataset from the user.
Step 3: To test if none of the elements of the said array is zero
Step 4: If zero is present print false otherwise print True.
Step 5: Display the output.
Step 6: Stop
PROGRAM:
import numpy as np
x = [Link]([1, 2, 3, 4])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print([Link](x))
x = [Link]([0, 1, 2, 3])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print([Link](x))

OUTPUT

Original array:
[1 2 3 4]
Test if none of the elements of the said array is zero:
True
Original array:
[0 1 2 3]
Test if none of the elements of the said array is zero:
False

RESULT:

Thus python program for implementing numpy module is executed and verified
successfully.
[Link](C) MATPLOTLIB
DATE:

AIM:
To write a python program to plot a graph using matplotlib library.

ALGORITHM:

Step 1: Start.
Step 2: To draw graph in python using matplot library.
Step 3: Get values for x and y axis.
Step 4: Label the x axis and y axis along with the title of the graph.
Step 5: Run using [Link]() for displaying graph.
Step 6: Stop
PROGRAM:
import [Link] as plt
x = [1,2,3]
y = [2,4,1]
[Link](x, y)
[Link]('x - axis')
[Link]('y - axis')
[Link]('My first graph!')
[Link]()

OUTPUT

RESULT:

Thus python program to plot a graph using matplotlib library is executed and verified
successfully.
[Link](D) SCIPY
DATE:

AIM:
To write a python program to implement scipy module in python.

ALGORITHM:

Step 1: Start.
Step 2: Create a 4x4 NumPy array filled with ones
Step 3: Use the savemat function from SciPy's io module to save the array to a
MATLAB file named "[Link]" under the variable name "ar".
Step 4: Use the loadmat function from SciPy's io module to load the MATLAB file back
into a Python variable named data. Treat MATLAB structs as Python objects.
Step 5: Access the array stored in the "ar" variable in the loaded data.
Step 6: Print the loaded array to verify the RESULT:s.
Step 7: Stop
PROGRAM:
import numpy as np
from scipy import io as sio
array = [Link]((4, 4))
[Link]("[Link]", {"ar": array})
data = [Link]("[Link]", struct_as_record=True)
data["ar"]

OUTPUT

array([[1., 1., 1., 1.],


[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]])

RESULT:

Thus python program to implement scipy module is executed and verified successfully.
IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS
[Link](A) USING FILE HANDLING
DATE:
COPY FROM ONE FILE TO ANOTHER

AIM:
To write a python program to implement file copying.

ALGORITHM:

Step 1: Start.
Step 2: Open the first file for reading and the second file for writing using the "with"
statement.
Step 3: Iterate through each line in the first file using a "for" loop.
a. Read each line from the first file.
b. Write the read line to the second file.
Step 4: Close both files automatically when the "with" block is exited.
Step 5: Stop
PROGRAM:
with open("[Link]","r") as firstfile, open("[Link]","w") as secondfile:
for line in firstfile:
[Link](line)

OUTPUT
RESULT:

Thus python program to implement scipy module in python is executed and verified
successfully.
[Link](B) WORD COUNT
DATE:

AIM:
To write a python program to implement word count in file operations.

ALGORITHM:

Step 1: Start.
Step 2: Request the user to input a string.
Step 3: Store the input string in a variable (e.g., test_string).
Step 4: Print the original string using the "print" statement.
Step 5: Use the "split" method on the input string to create a list of words.
Step 6: Use the "len" function to find the number of words in the list.
Step 7: Store the RESULT: in a variable (e.g., res).
Step 8: Print the number of words in the string using the "print" statement.
Step 9: Stop
PROGRAM:

test_string = input("Enter the string:")


print ("The original string is : " + test_string)
res = len(test_string.split())
# printing RESULT:
print ("The number of words in string are : " + str(res))

OUTPUT

Enter the string: Hi this is Ram


The original string is : Hi this is Ram
The number of words in string are : 4

RESULT:

Thus python program to implement word count in file operations is executed and verified
successfully.
[Link](C) LONGEST WORD
DATE:

AIM:
To write a python program to implement longest word in file operations.

ALGORITHM:

Step 1: Start.
Step 2: Request the user to input a sentence and store it in the variable "sentence."
Step 3: Split the sentence into a list of words using the "split" method and store the
RESULT: in a variable "words_list."
Step 4: Find the longest word in "words_list" using the "max" function with the "key"
parameter set to "len" and store the RESULT: in a variable "longest."
Step 5: Print "Longest word is: " followed by the value of "longest."
Step 6: Print "And its length is: " followed by the length of the "longest" word using the
"len" function.
Step 7: Stop
PROGRAM:

sentence = input("Enter sentence: ")


longest = max([Link](), key=len)
print("Longest word is: ", longest)
print("And its length is: ", len(longest))

OUTPUT

Enter sentence: Information security is securing information


Longest word is: Information
And its length is: 11

RESULT:

Thus python program to implement longest word in file operations is executed and
verified successfully.
IMPLEMENTING REAL-TIME/TECHNICAL
[Link](A) APPLICATIONS USING EXCEPTION HANDLING
DATE:
DIVIDE BY ZERO ERROR

AIM:
To write exception handling program using python to depict the zero error.

ALGORITHM:

Step 1: Start.
Step 2: Define a function named zero_exception():
a. Inside the function:
i. Use a "try" block to attempt the following:
- Prompt the user to input the first number and store it in the variable x.
- Prompt the user to input the second number and store it in the variable y.
- Perform division of x by y and store the RESULT: in the variable
RESULT:.
- Print the RESULT:.
ii. Use an "except" block to catch any exception (e.g., DivisionError) that
might occur:
- Print an error message indicating that division by zero has occurred.
Step 3: Call the zero_exception() function to execute the code.
Step 4: Stop
PROGRAM:
def zero_exception():
try:
x=int(input("Enter the first number:"))
y=int(input("Enter the second number:"))
print(x/y)
except Exception as e:
print("Error:divided by zero!")
zero_exception()

OUTPUT

Enter the first number: 5


Enter the second number: 0
Error:divided by zero!
Enter the first number: 10
Enter the second number: 5
2.0

RESULT:

Thus exception handling program using python to depict the zero error is executed and
verified successfully.
[Link](B) VOTER’S AGE VALIDITY
DATE:

AIM:
To write exception handling program using python to depict the voters eligibility.

ALGORITHM:

Step 1: Start.
Step 2: Prompt the user to input their age and store it in the variable "age."
Step 3: Convert the input to an integer using the "int" function.
Step 4: Check if the age is greater than 18:
i. If true, print "Eligible to Vote."
ii. If false, print "Not Eligible to Vote."
Step 5: Handle any exceptions that might occur during the execution of the "try" block:
a. Print "Age must be a valid number."
Step 6: Stop
PROGRAM:
try:
age=int(input("Enter your age:"))
if age>18:
print("Eligible to Vote")
else:
print("\n Not Eligible to Vote")
except:
print("Age must be Valid number")

OUTPUT

Enter your age: 12


Not Eligible to Vote

Enter your age: 19


Eligible to Vote

RESULT:

Thus exception handling program using python to depict the voter’s eligibility is
executed and verified successfully.
[Link](C) STUDENT MARK RANGE VALIDATION
DATE:

AIM:
To write python program to validate the student mark range.

ALGORITHM:

Step 1: Start.
Step 2: Prompt the user to input their mark.
Step 3: Convert the input to an integer and store it in the variable `mark`.
Step 4: If a ValueError occurs during the conversion:
a. Print "Mark must be a valid number."
b. Go to step 6.
Step 5: Check if the mark is within the valid range (50 to 100, inclusive):
a. If true, print "Pass and your mark is valid.
b. If false, print "Fail and your mark is not valid."
Step 6: End the try block.
Step 7: If any other exception occurs,Print "Error occurred: <exception_message>.
Step 8: Stop
PROGRAM:
def main():
try:
mark=int(input("Enter your mark:"))
if mark>=50 and mark<=100:
print("Pass and your mark is valid")
else:
print("Fail and your mark is valid")
except ValueError:
print("Mark must be a valid number")
except IOError:
print("Enter valid mark")
except:
print("Error occured")
main()

OUTPUT

Enter your mark: 65


Pass and your mark is valid

Enter your mark: 40


Fail and your mark is valid

Enter your mark: 5a


Mark must be a valid number

Enter your mark: 0.5


Mark must be a valid number

RESULT:

Thus python program to validate the student mark range is executed and verified
successfully.
[Link] EXPLORING PYGAME TOOL
DATE:

AIM:
To write python program to implement pygame.

ALGORITHM:

Step 1: Start.
Step 2: Initialize Pygame:
a. Import the pygame module.
b. Call [Link]().
Step 3: Create a Pygame window:
a. Set the window size to [500, 500] using [Link].set_mode() and
store it in the variable 'screen'.
Step 4: Create a clock object for controlling the frame rate:
a. Create a clock object using [Link]() and store it in the variable
'clock'.
Step 5: Set up the main loop:
a. Set the variable 'running' to True.
b. Enter a while loop with the condition 'while running:'
Step 6: Handle Pygame events:
a. Inside the loop, iterate over each event using a for loop and
[Link]().
b. If the event type is [Link], set 'running' to False to exit the loop
Step 7: Clear the screen: Outside the event loop, fill the screen with a white color using
[Link]((255, 255, 255)).
Step 8: Use [Link]() to draw a red circle at the coordinates (250, 250) with a
radius of 200.
Step 9: Use [Link]() to update the display.
Step 10: Use [Link](60) to control the frame rate to 60 frames per second.
Step11: End the main loop.
Step 12: Call [Link]() to clean up and quit Pygame.
Step 13: Sto
PROGRAM:
import pygame
[Link]()
screen = [Link].set_mode([500, 500])
running = True
while running:
for event in [Link]():
if [Link] == [Link]:
running = False
[Link]((255, 255, 255))
[Link]()
[Link](screen, (255, 0, 0), (250, 250),200)
[Link]()

OUTPUT

RESULT:

Thus python program to implement pygame tool is executed and verified successfully.
DEVELOPING A GAME ACTIVITY USING PYGAME
[Link](A)
DATE: BOUNCING BALL

AIM:
To write python program to implement bouncing ball using pygame tool.

ALGORITHM:

Step 1: Start.
Step 2: Initialize Pygame, set up the screen, and define ball parameters.
Step 3: Create a clock object for controlling the frame rate.
Step 4: Enter the game loop:
a. Handle events and exit if the window is closed.
b. Update ball position, handle collisions, and draw on the screen.
c. Update the display and control the frame rate.
Step 5: Quit Pygame when the loop exits.
Step 6: Stop
PROGRAM:
import pygame
# initialize pygame
[Link]()
# define width of screen
width = 1000
# define height of screen
height = 600
screen_res = (width, height)
[Link].set_caption("GFG Bouncing game")
screen = [Link].set_mode(screen_res)
# define colors
red = (255, 0, 0)
black = (0, 0, 0)
# define ball
ball_obj = [Link](
surface=screen, color=red, center=[100, 100], radius=40)
# define speed of ball
# speed = [X direction speed, Y direction speed]
speed = [1, 1]
# game loop
while True:
# event loop
for event in [Link]():
# check if a user wants to exit the game or not
if [Link] == [Link]:
exit()
# fill black color on screen
[Link](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
[Link](surface=screen, color=red,
center=ball_obj.center, radius=40)
# update screen
[Link]()
[Link](60

OUTPUT

RESULT:

Thus python program to implement bouncing ball using pygame tool is executed and
verified successfully.
DEVELOPING A GAME ACTIVITY USING PYGAME
[Link](B)
DATE: CAR RACE

AIM:
To write python program to implement car game using pygame tool.

ALGORITHM:

Step 1: Start.
Step 2: Initialize Pygame, set up the screen, and load car image.
Step 3: Set initial car and enemy car positions
Step 4: Enter the game loop:
a. Handle events for player movement.
b. Move and draw the enemy car.
c. Check for collisions and update display.
d. Control the frame rate.
Step 5: Quit Pygame when the loop exits.
Step 6: Stop
PROGRAM:
import pygame
import sys
import random
# Initialize Pygame
[Link]()
# Set up the screen
width, height = 800, 600
screen = [Link].set_mode((width, height))
[Link].set_caption("Car Race Game")
# Set up colors
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# Load car image
car_image = [Link]('[Link]') # Make sure to replace '[Link]' with the actual image
file
# Set up initial car position
car_width = 73
car_x = width // 2 - car_width // 2
car_y = height - 100
# Set up initial enemy car position
enemy_car_width = 73
enemy_car_x = [Link](0, width - enemy_car_width)
enemy_car_y = -600
enemy_car_speed = 5
# Set up clock for controlling frame rate
clock = [Link]()
# Define functions
def car(x, y):
[Link](car_image, (x, y))
def game_loop():
global car_x, car_y, enemy_car_x, enemy_car_y, enemy_car_speed
game_over = False
while not game_over:
for event in [Link]():
if [Link] == [Link]:
[Link]()
[Link]()
keys = [Link].get_pressed()
if keys[pygame.K_LEFT] and car_x > 0:
car_x -= 5
if keys[pygame.K_RIGHT] and car_x < width - car_width:
car_x += 5
[Link](white)
# Move enemy car
enemy_car_y += enemy_car_speed
# Check for collisions
if car_x < enemy_car_x + enemy_car_width and car_x + car_width > enemy_car_x \
and car_y < enemy_car_y + 100 and car_y + 100 > enemy_car_y:
game_over = True
# Draw enemy car
[Link](screen, red, [enemy_car_x, enemy_car_y, enemy_car_width, 100])
# Draw player's car
car(car_x, car_y)
# Update the display
[Link]()
# Set the frame rate
[Link](60)
# Run the game loop
game_loop()

OUTPUT

RESULT:

Thus python program to implement car race using pygame tool is executed and verified
successfully.

You might also like