0% found this document useful (0 votes)
5 views

Lab Manual

The document is a lab manual for Prathyusha Engineering College's Python programming course, detailing various experiments related to problem-solving using Python. It includes flowcharts and algorithms for real-life applications such as electricity billing, retail shop billing, and scientific computations, along with programming exercises involving conditionals, loops, and data structures. Each section provides aims, algorithms, sample programs, and results for verification.

Uploaded by

sanjayraams99
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Lab Manual

The document is a lab manual for Prathyusha Engineering College's Python programming course, detailing various experiments related to problem-solving using Python. It includes flowcharts and algorithms for real-life applications such as electricity billing, retail shop billing, and scientific computations, along with programming exercises involving conditionals, loops, and data structures. Each section provides aims, algorithms, sample programs, and results for verification.

Uploaded by

sanjayraams99
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

PRATHYUSHA ENGINEERING COLLEGE

(An Autonomous Institution)


LAB MANUAL
241GES214L
PROBLEM SOLVING USING PYTHON
LABORATORY
INDEX
S,NO DATE EXPERIMENT PG.NO MARK SIGN

01 Identification and solving of


simple real life or scientific or
technical problems, and
developing flow charts for the
same

02 Python programming using


simple statements and expressions

03 Scientific problems using


Conditionals and Iterative loops.

04 Implementing real-time/technical
applications using Lists, Tuples.

05 Implementing real-time/technical
applications using Sets,
Dictionaries.

06 Implementing programs using


Functions.

07 Implementing programs using


Strings.

08 Implementing programs using


written modules and Python
Standard Libraries

09 Implementing real-time/technical
applications using File handling.

10 Implementing real-time/technical
applications using Exception
handling.

11 Exploring Pygame tool.

12 Developing a game activity


using Pygame like bouncing
ball, car race etc.
EXP NO:1

Identification and solving of simple real life or scientific or technical problems, and
developing flow charts for the same.(Electricity Billing, Retail shop billing, Sin series,
weight of a motorbike, Weight of a steel bar, compute Electrical Current in Three Phase
AC Circuit, etc.)

a. Flowchart for Electricity Bill Calculation

Aim :

To draw the flowchart for Electricity bill calculation with the following rates for its
customers: -

No. of unit consumed Charges/unit (RM)


1-200 2.50
201 - 500 3.50 over
501 5.00

Draw a flowchart to calculated the net amount of the bill for each consumer and print it.

Algorithm :

Step 1 : Start
Step 2 : Read the unit values
Step 3 : Check 1<=unit<=200
Then calculate total_charges=unit*2.50
Step 4 : Check 201<=unit<=500
Then calculate total_charges=unit*3.50
Step 5 : Check unit>500
Then calculate total_charges=unit*5.0
Step 6 : print total_charges
Step 7 : Stop
Flowchart:

RESULT:

Thus Flowchart is verified .


b. Flowchart for retail shop bill calculation

Aim :

To draw a flowchart for retail bill preparation

Algorithm :

Step 1: Start

Step 2: Read item name

Step 3: Read price per unit

Step 4: Read No of Quantity

Step 5: Compute Totalcost=Quantity*price per unit

Step 6: Display total

Step 7: Read payment

Step 8: Compute paychange=payment-Totalcost

Step 9: Display the items,payment and paychange

Step 10: Stop


Flowchart:

RESULT:

Thus Flowchart is verified


c. Flowchart for computing sin series

Aim :

To draw a flowchart for computing sin series

Algorithm :

Step 1: Take in the value of x in degrees and the number of terms and store it in separate

variables.

Step 2: Pass these values to the sine function as arguments.

Step 3: Define a sine function and using a for loop, first convert degrees to radians.

Step 4: Then use the sine formula expansion and add each term to the sum variable.

Step 5: Then print the final sum of the expansion.

Step 6: Stop
Flowchart:

RESULT:

Thus Flowchart is verified


d. Flowchart for calculating the weight of a motorbike

Aim :

To draw a flowchart for weight of a motorbike.

Algorithm :

Step 1: Start

Step 2: Read D,L

Step 3: Compute w=D**2L/162

Step 4: Print w Step

5: Stop
Flowchart:

START

READ D,L

COMPUTE W= D**2*L/162

DISPLAY W

STOP

RESULT:

Thus Flowchart is verified


e. Flowchart for calculating the weight of a Steelbar

Aim :

To draw a flowchart for weight of a steel bar

Algorithm :

Step 1: Start

Step 2: Read LBS

Step 3: Compute w=LBS/2.2046

Step 4: Print w

Step 5: Stop

Flowchart:
START

READ
LBS

COMPUTE
W=LBS/2.2046

DISPLAY
W

STOP

RESULT:

Thus Flowchart is verified


f. Flowchart for calculating the compute Electrical Current in Three Phase AC Circuit

Aim :

To draw a flowchart for compute Electrical Current in Three Phase AC Circuit

Algorithm :

Step 1: Start

Step 2: Read kva,voltage

Step 3: Compute current=kva/voltage

Step 4: Print current

Step 5: Stop

Flowchart:

START

READ KVA,
Voltage

COMPUTE Current= KVA/Voltage

DISPLAY
Current

STOP

RESULT:

Thus Flowchart is verified


1. Ex. 2. Python programming using simple statements and expressions (exchange the
values of two variables, circulate the values of n variables, distance between two points).

2(a). Exchange the value of two variables

Aim:

To write python programs using exchange the values of two variables

Algorithm:

STEP 1: Read the values of P and Q


STEP 2: temp = P
STEP 3: P = Q

STEP 4: temp = P

STEP 5: PRINT P, Q

Program:

P= int( input("Please enter value for P: "))

Q = int( input("Please enter value for Q: "))

temp= P

P=Q

P= temp print ("The Value of P after

swapping: ", P)

print ("The Value of Q after swapping: ",Q)


Output:

Please enter value for P: 5

Please enter value for Q: 7

The Value of P after swapping: 7

The Value of Q after swapping: 5

RESULT:

Thus the program and Output successful verified.

2 (b) Circulate ‘n’ values

Aim:

To write python programs using circulate the values of n variables

Algorithm:

STEP 1: Read the values to be circulated in a list

STEP 2: Read the number of times of shifting in n

STEP 3: Using list slicing, perform rotation

STEP 4: Print (list[n:]+list[:n])

STEP 5: Stop

Program:

list=[10,20,30,40,50]

n=2

print(list[n:]+list[:n])
Output:

[30, 40, 50, 10, 20]

RESULT:

Thus the program and Output successful verified.

2 (c) Distance between two points

Aim:

To write python programs using Distance between two points

Algorithm:

STEP 1: Read the values of x1,x2 and y1,y2

STEP 2: Import math module to calculate the square root

STEP 3: Compute the distance using the formula

STEP 4: Using the formula, find square root of ( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2) )

STEP 5: Print the result

STEP 6: Stop

Program:

import math p1 = [4, 0]

p2 = [6, 6]

distance = math.sqrt( ((p1[0]-p2[0])**2)+((p1[1]-p2[1])**2) )

print(distance)
Output:

6.324555320336759

RESULT:

Thus the program and Output successful verified.

3.Scientific problems using Conditionals and Iterative loops. (Number series, Number
Patterns, pyramid pattern)

3(a). Biggest of three numbers

Aim:

To write python programs using conditional statements and loops.

Algorithm:

Step 1: Ask the user to enter three integer values.

Step 2: Read the three integer values in num1, num2, and num3.

Step 3: Check if num1 is greater than num2.

If true, then check if num1 is greater than num3.

If true, then print ‘num1’ as the greatest number.

Step 4: If false, then print ‘num3’ as the greatest number.

If false, then check if num2 is greater than num3.

If true, then print ‘num2’ as the greatest number.

If false, then print ‘num3’ as the greatest number Step

5: Stop
Program:

num1 = float(input("Enter first number: "))

num2 = float(input("Enter second number: "))

num3 = float(input("Enter third number: "))

if (num1 > num2) and (num1 > num3):

largest = num1

elif (num2 > num1) and (num2 > num3):

largest = num2

else:

largest = num3

print("The largest number is",largest)

Output:

Enter first number: 55

Enter second number: 64

Enter third number: 34

The largest number is 64.0

RESULT:

Thus the program and Output successful verified.

3 (b) Sum of digits of a number

Aim:
To write python programs using conditional statements and loops.

Algorithm:

Step 1: User must first enter the value and store it in a variable.

Step 2: The while loop is used and the last digit of the number is obtained by using the
modulus operator.

Step 3: The digit is added to another variable each time the loop is executed.

Step 4: This loop terminates when the value of the number is 0.

Step 5: The total sum of the number is then printed.

Step 6: Stop

Program:

n=int(input("Enter a number:"))

tot=0

while(n>0):

dig=n%10

tot=tot+dig

n=n//10

print("The total sum of digits is:",tot)

Output:

Enter a number:456

The total sum of digits is: 15

RESULT:

Thus the program and Output successful verified.


3 (c) Perfect Number or Not

Aim:

To write python programs using conditional statements and loops.

Algorithm:

Step 1: Start

Step 2: Read n

Step 3: Initialize s=0 Step

4: for i=1 to n do

if(n%i)==0, then

s=s+i

Step 5: if s==n then Print "Given Number is Perfect Number". Goto

Step 7 Step 6: Print "Given Number is Not a Perfect Number"

Step 7: Stop

Program:

Number = int(input(" Please Enter any Number: "))

Sum = 0

for i in range(1, Number):

if(Number % i == 0):

Sum = Sum + i if (Sum == Number):

print(" %d is a Perfect Number" %Number)

else:

print(" %d is not a Perfect Number" %Number)


Output:

Please Enter any Number: 6

6 is a Perfect Number

RESULT:

Thus the program and Output successful verified.

3 (d) Printing Fibonacci Series

Aim:

To write python programs using conditional statements and loops.

Algorithm:

Step 1: Start

Step 2: Declare variables i, t1,t2 , sum

Step 3: Initialize the variables, t1=0, t2=1, and sum=0

Step 4: Enter the number of terms of Fibonacci series to be printed Step 5: Print First two
terms of series

Step 6: Use loop for the following steps

-> sum=t1+t3

-> t1=t2

-> t2=sum

-> increase value of i each time by 1

-> print the value of show

Step 7: Stop
Program:

n = int(input("Enter the value of 'n': "))

t1 = 0

t2 = 1

sum = 0

count = 1

print("Fibonacci Series: ")

while(count <= n):

print(sum, end = " ")

count += 1

t1 = t2

t2 = sum

sum = t1 + t2

Output:

Enter the value of 'n': 7

Fibonacci Series:

0112358

RESULT:

Thus the program and Output successful verified.


3 (e ) Print Different Patterns in python

Aim:

To write python programs using conditional statements and loops.

Algorithm:

STEP 1: Read the row and column values

STEP 2: Using nested loops, print the required pattern

STEP 3: Stop

Program 1:

num_rows = int(input("Enter the number of rows"));

for i in range(0, num_rows):

for j in range(0, num_rows-i-1):

print(end=" ")

for j in range(0, i+1):

print("*", end=" ")

print()

Output:

Enter the number of rows5

*
**
***
****
*****
Program 2:

num_rows = int(input("Enter the number of rows"));

k=1
for i in range(0, num_rows):

for j in range(0, k):

print("* ", end="")

k=k+1

print()

Output:

Enter the number of rows5

**

***

****

*****

Program 3:

num_rows = int(input("Enter the number of rows"));

k=8

for i in range(0, num_rows):

for j in range(0, k): print(end=" ")

k = k - 2 for j in

range(0, i+1):
print("* ", end="")

print()

Output:

Enter the number of rows5

* *

* **

* ***

* ****

Program 4:

num_rows = int(input("Please enter the number of rows"));

for i in range(num_rows,0,-1):

for j in range(0, num_rows-i):

print(end=" ")

for j in range(0,i):

print("* ", end=" ")

print()

Output:

Please enter the number of rows5

* * * * *

* * * *
* * *

* *

Program 5:

rows = 6

for i in range(rows):

for j in range(i):

print(i, end=' ')

print('')

Output:

222

3 323

4 4 426

5 5 5 526

RESULT:

Thus the program and Output successful verified.

3 (f ) Pascals Triangle

Aim:

To write python programs using conditional statements and loops.

Algorithm:
STEP 1: Read the number of rows to be printed

STEP 2: Using nested loop, print the spaces needed

STEP 3: Using binomial coefficient, print the values

STEP 4: Stop

Program:

n = int(input("Enter the rows:"))

for i in range(1, n+1):

for j in range(0, n-i+1):

print(' ', end='')

C=1

for j in range(1, i+1):

print(' ', C, sep='', end='')

C = C * (i - j) // j

print()

Output:

Enter the rows:5

11

121

1331

14641

RESULT:

Thus the program and Output successful verified.


3 (g) Alphabet Patterns in Python

Aim:

To write python programs using conditional statements and loops.

Algorithm:

STEP 1: Read the row and column values

STEP 2: Using nested loops, print the required pattern

STEP 3: Stop

Program 1:

for i in range (65,70):

# inner loop

for j in range(65,i+1):

print(chr(j),end="")

print()

Output:

AB

ABC

ABCD

ABCDE
Program 2:

for i in range(65,70):

k=i

# Inner loop

for j in range(65,i+1):

print(chr(k),end="")

k=k+1

print()

Output:

BC

CDE

DEFG

EFGHI

Program 3:

str= input("Enter your name:")

for i in range(0,len(str)):

for j in range(0,i+1):

print(str[j],end="")

print()
Output:

Enter your name:Ajin

Aj

Aji Ajin

program4

n = int(input("Enter the row"))

for i in range(n):

# printing spaces

for j in range(i):

print(' ', end='')

# printing alphabet

for j in range(2*(n-i)-1):

print(chr(65 + j), end='')

print()

Output:

Enter the row5

ABCDEFGHI

ABCDEFG

ABCDE

ABC

A
Program 5:

n=5

# upward pyramid

for i in range(n):

for j in range(n - i - 1):

print(' ', end='')

for j in range(2 * i + 1):

print(chr(65 + j), end='')

print() for i in range(n - 1):

for j in range(i + 1):

print(' ', end='')

for j in range(2*(n - i - 1) - 1):

print(chr(65 + j), end='')

print()

Output:

A
ABC
ABCDE
ABCDEFG
ABCDEFGHI
ABCDEFG
ABCDE
ABC
A

RESULT:

Thus the program and Output successful verified.


3 (h) Prime Numbers in a range

Aim:

To write python programs using conditional statements and loops.

Algorithm:

Step 1: Start

Step 2: Read lower and upper range

Step 3: Using a for loop, iterate on all the numbers in the range

Step 4 : For each number, check if its prime or not

Step 5 : If the number is prime, print

Else skip

Step 6 : Stop

Program:

lower = 900 upper = 1000

print("Prime numbers between", lower, "and", upper, "are:")

for num in range(lower, upper + 1):

if num> 1:

for i in range(2, num):

if (num % i) == 0:

break

else:

print(num)
Output:

Prime numbers between 900 and 1000 are:

907

911

919

929

937

941

947

953

967

971

977

983

991

997

RESULT:

Thus the program and Output successful verified.

4. Implementing real-time/technical applications using Lists, Tuples. (Items present in a


library/Components of a car/ Materials required for construction of a building –
operations of list & tuples)
4(a). Display the Book details using a list

Aim:

To write python programs using Lists and Tuples.

Algorithm:

Step 1: Start

Step 2: Create an empty list

Step 3: Print the menu and read the choice

Step4 : If the choice is 1, read the book name from the user and append to list

Step 5: If the choice is 2, print the books in the list

Step 6: Stop

Program:

my_book=[]

ch='y'

while(ch=='y'):

print('''

1. Add New Book

2. Display Books

''')

choice=int(input("Enter choice: "))

if(choice==1):

book=input("Enter the name of the book:")

my_book.
append(book)

elif(choice==2):

for i in my_book:

print(i)

else:

print("Invalid choice!")

ch=input("Do you want to continue...?")

print("Bye!")

Output:

1. Add New Book 2.

Display Books

Enter choice: 1

Enter the name of the book:Python programming

Do you want to continue...?y

RESULT:

Thus the program and Output successful verified.

4(b). Automobile Components using Lists

Aim:

To write python programs using Lists and Tuples.

Algorithm:

Step 1: Start
Step 2: Create a list of components of automobile

Step 3: Print the menu and read the choice

Step 4 : If the choice is 1, display the main components in the list

Step 5: If the choice is 2, print the components of list

Step 6: If the choice is 3, Print the total components

Step 7: If the choice is 4, arrange the components in order

Step : Stop

Program:

components=['RADIATOR','AC
COMPRESSOR','BATTERY','ALTERNATOR','AXLE','BRAKES','SHOCK

ABSORBERS','TRANSMISSION','FUEL TANK']

components1=['CATALYTIC CONVERTER','MUFFLER','TAILPIPE']

ch='y'

while(ch=='y'):

print('''

1. Display Main Components

2. Display All Components

3. Total Components

4. Components in Alphabetical Order

''')

choice=int(input("Enter choice: "))

if(choice==1):

print("The Main components are:")

print(components)

elif(choice==2):
print("The components are:")

print(components+components1)

elif(choice==3):

print("The components are:")

print("Main Components:",len(components))

print("Other Components:",len(components1))

elif(choice==4):

print("The components in alphabetical order are:")

components.sort()

print("MainComponents:",components)

print("Sorted order")

else:

print("Invalid choice!")

ch=input("Do you want to continue...?")

print("Bye!")

Output:

1. Display Main Components

2. Display All Components

3. Total Components

4. Components in Alphabetical Order

Enter choice: 4

The components in alphabetical order are:

Main Components: ['AC COMPRESSOR', 'ALTERNATOR', 'AXLE', 'BATTERY',


'BRAKES', 'FUEL TANK', 'RADIATOR', 'SHOCK ABSORBERS', 'TRANSMISSION']
Sorted order

Do you want to continue...?

RESULT:

Thus the program and Output successful verified.

4(c). Materials of Construction using Tuple

Aim:

To write python programs using Lists and Tuples.

Algorithm:

Step 1: Start

Step 2: Create a tuple of construction materials

Step 3: Print the menu and read the choice

Step 4 : If the choice is 1, display the materials in the tuple

Step 5: If the choice is 2, display the types of materials in the tuple

Step 6: If the choice is 3, Print the reverse order of materials

Step 7: If the choice is 4, print the total number

Step 8: If the choice is 5, print any material at random

Step 9: Stop

Program:

types=('Artificial Materials','Natural Materials')

material=('Cement','Aggregates','Stones and Rocks','Mud and Clay',

'Concrete','Bricks','Glass','Plastic','Structural Steel',
'Foam','Fabric','Thatch','Timber and Wood','Tiles (Ceramics)',

'Electrical Items')

ch='y'

while(ch=='y'):

print('''

1. Display Materials

2. Display types of Materials

3. Display Reverse order of materials

4. Count of Needed materials

5. Choose a material at random

''')

choice=int(input("Enter choice: "))

if(choice==1):

print(material)

elif(choice==2):

print(types)

elif(choice==3):

print(material[::-1])

elif(choice==4):

print(len(material))

elif(choice==5):

print(material[5])

else:
print("Invalid choice!")

ch=input("Do you want to continue...?")

print("Bye!")

Output:

1. Display Materials

2. Display types of Materials

3. Display Reverse order of materials

4. Count of Needed materials

5. Choose a material at random

Enter choice: 4

15

Do you want to continue...?y

1. Display Materials

2. Display types of Materials

3. Display Reverse order of materials

4. Count of Needed materials

5. Choose a material at random

Enter choice: 5

Bricks

Do you want to continue...?

RESULT:

Thus the program and Output successful verified.


4(d). List Operations

Aim:

To write python programs using Lists and Tuples.

Algorithm:

Step 1: Start

Step 2: Create a list of items

Step 3: Print the output for each of the operations

Indexing, extend, pop, slicing, clear, remove and del

Step 4: Stop

Program:

numbers = [11, 22, 33, 100, 200, 300]

print(numbers[0]) print(numbers[5])

print(numbers[1]) print(numbers[-1])

print(numbers[-3]) print(numbers[-4])

n_list = ["hello", "world", "hi", "bye"]

print(n_list[1:3])

print(n_list[:3])

print(n_list[3:])

print(n_list[:])

n_list.insert(3, 100)
print(n_list)

n_list.append(99) print(n_list)

n_list.extend([11, 22]) print(n_list)

n_list[2] = 100 print(n_list)

n_list[1:4] = [11, 22, 33] print(n_list)

del n_list[2:4] print(n_list)

ch_list = ['A', 'F', 'B', 'Z', 'O', 'L']

ch_list.remove('B')

print(ch_list) ch_list.pop(1)

print(ch_list) ch_list.clear()

print(ch_list)

Output:

11

300

22

300

100

33

['world', 'hi']

['hello', 'world', 'hi']

['bye']

['hello', 'world', 'hi', 'bye']


['hello', 'world', 'hi', 100, 'bye']

['hello', 'world', 'hi', 100, 'bye', 99]

['hello', 'world', 'hi', 100, 'bye', 99, 11, 22]

['hello', 'world', 100, 100, 'bye', 99, 11, 22] ['hello', 11, 22, 33, 'bye', 99, 11, 22]

['hello', 11, 'bye', 99, 11, 22]

['A', 'F', 'Z', 'O', 'L']

['A', 'Z', 'O', 'L']

[]

RESULT:

Thus the program and Output successful verified.

4(e). List Operations

Aim:

To write python programs using Lists and Tuples.

Algorithm:

Step 1: Start

Step 2: Create a tuple of items

Step 3: Print the output for each of the operations

Type, del, sum, max, min, sorted, packing, slicing, indexing, membership Step 4:

Stop

Program:

type1 = (1, 3, 4, 5, 'test')


print (type1)

tuple1 = ('a', 'b', 1, 3, [5, 'x', 'y', 'z'])

print(tuple1[0])

print(tuple1[4][1])

print(tuple1[-1]) print(tuple1[2:5])

Tuple1 = (1, 3, 4)

Tuple2 = ('red’, ’green’, ‘blue')

Tuple3 = (Tuple1, Tuple2)

print (Tuple3) del (Tuple2)

print (1 in Tuple1)

print(5inTuple1)

print(max(Tuple1))

print(sum(Tuple1))

print(sorted(Tuple1))

person = ("Sai", '5 ft', "Actor")

(name, height, profession) = person

print(name)

print(height)

print(profession)

Output:

(1, 3, 4, 5, 'test')

ax

[5, 'x', 'y', 'z']


(1, 3, [5, 'x', 'y', 'z'])

((1, 3, 4), 'red", ’green’, "blue')

True

False

[1, 3, 4]

Sai

5 ft

Actor

RESULT:

Thus the program and Output successful verified.

5.Implementing real-time/technical applications using Sets, Dictionaries. (Language,


components of an automobile, Elements of a civil structure, etc.- operations of Sets &
Dictionaries)

5(a) Components of an automobile using Set Operations

AIM:
To write a python program for to add ,remove and pop the automobile components using
python set operations.

ALGORITHM:

1. Start the Program


2. Initialize the empty dictionary with components {}
3. Print the type of components {} so that dictionary type will be printed.
4. Initialize the components as set()
5. Add the values of automobile components to the set.
6. Get the extra component to be added to the set as input.
7. Add the extra component through add() method.
8. Print the set as components
9. Remove any one component from the set using pop() method.
10. Print the updated components.
11. Stop the Program.

PROGRAM:
components={}
print(type(components))
components=set()
print(type(components))
components={"Clutch","Gear Box ","Front dead axle","Engine","Rear drive
axle","Differential"}
print(components)
b=input("Enter the components to be added" )
components.add(b)
print("Components of automobile after adding an element in set")
print(components)
print("Removing the one Component")
components.pop()
print("Updated Components after removing an element is set")
print(components)

OUTPUT:
<class 'dict'>
<class 'set'>
{'Gear Box ', 'Front dead axle', 'Engine', 'Clutch', 'Differential', 'Rear drive axle'}
Enter the components to be addedAxle
Components of automobile after adding an element in set
{'Gear Box ', 'Front dead axle', 'Engine', 'Clutch', 'Differential', 'Rear drive axle', 'Axle'}
Removing the one Component
Updated Components after removing an element is set
{'Front dead axle', 'Engine', 'Clutch', 'Differential', 'Rear drive axle', 'Axle'}

RESULT:

Thus the program and Output successful verified.

5.(b) Elements of a civil structure using dictionaries

AIM:
To implement Elements of a civil structure using dictionaries in python

ALGORITHM:
1.Start the Program.
2. Create the empty dictionary with Elements_dictionary
3. Add the elements to dictionary with the key values.
4. Print the type of Elements_dictionary
5. Display the elements in the dictionary.
6. Remove the particular item in the Elements_dictionary by using key with pop() method.
7.Display the popped element in the civil structure
8. Add the single element into the Elements_dictionary
9. Display the modified dictionary elements.
10.Stop the Program

PROGRAM:
# Elements of a civil structure
Elements_dictionary = {}
# dictionary with integer keys
Elements_dictionary = {1: 'Roof', 2:
'Parapet',3:'Lintels',4:'Beams',5:'Columns',6:'Walls',7:'Floor',8:'Stairs'}
print(type(Elements_dictionary))
print("The dictionary elements of Civil Structure")
print(Elements_dictionary)
print("Remove the particular item in the Civil structure")
print(Elements_dictionary.pop(4))
Elements_dictionary[9]='Plinth Beam'
print("The Dictionary Elements after adding one elements in Civil Structure")
print(Elements_dictionary)

OUTPUT:
<class 'dict'>
The dictionary elements of Civil Structure
{1: 'Roof', 2: 'Parapet', 3: 'Lintels', 4: 'Beams', 5: 'Columns', 6: 'Walls', 7: 'Floor', 8: 'Stairs'}
Remove the particular item in the Civil structure
Beams
The Dictionary Elements after adding one elements in Civil Structure
{1: 'Roof', 2: 'Parapet', 3: 'Lintels', 5: 'Columns', 6: 'Walls', 7: 'Floor', 8: 'Stairs', 9: 'Plinth
Beam'

RESULT:

Thus the program and Output successful verified.

5(c) Add and Search student record using dictionary

AIM:
To implement a python Program to search student record using dictionary

ALGORITHM:
1.Create a list to store the student details
2. Read the data such as rno, name, marks
3. Calculate the total, average
4. Convert the list to the dictionary
5. Print the student information’s
6. Stop the Program.
PROGRAM:
n = int(input("Please enter number of students:"))
all_students = []
for i in range(0, n):
stud_name = input('Enter the name of student: ')
print (stud_name)
stud_rollno = int(input('Enter the roll number of student: '))
print (stud_rollno)
mark1 = int(input('Enter the marks in subject 1: '))
print (mark1)
mark2 = int(input('Enter the marks in subject 2: '))
print (mark2)
mark3 = int(input('Enter the marks in subject 3: '))
print (mark3)
total = (mark1 + mark2 + mark3)
print("Total is: ", total) average = total / 3
print ("Average is :", average)
all_students.append({ 'Name': stud_name,
'Rollno': stud_rollno,
'Mark1': mark1,
'Mark2': mark2,
'Mark3': mark3,
'Total': total,
'Average': average
})

for student in all_students:


print ('\n')
for key, value in student.items():
print (key, value)

OUTPUT:
ENTER ZERO NUMBER FOR EXIT !!!!!!!!!!!! ENTER
STUDENT INFORMATION ------------------------
enter roll no.. :: -- 1 enter
marks 1 :: -- 77 enter
marks 2 :: -- 88 enter
marks 3 :: -- 77
Please enter number of students:2
Enter the name of student: Alex
Alex
Enter the roll number of student: 1
1
Enter the marks in subject 1: 99
99
Enter the marks in subject 2: 88
88
Enter the marks in subject 3: 88
88
Total is: 275
Average is : 91.66666666666667
Enter the name of student: Avin
Avin
Enter the roll number of student: 2
2
Enter the marks in subject 1: 77
77
Enter the marks in subject 2: 77
77
Enter the marks in subject 3: 77
77
Total is: 231
Average is : 77.0

Name Alex
Rollno 1
Mark1 99
Mark2 88
Mark3 88
Total 275
Average 91.66666666666667

Name Avin
Rollno 2
Mark1 77
Mark2 77
Mark3 77
Total 231
Average 77.0

RESULT:

Thus the program and Output successful verified.

5(d) Operations in a set using Components of a Language

Aim:

To Implement operations in a set using Components of a Language as example.

ALGORITHM:

1. Start the Program


2. Initialize the dictionaries L1, L2
3. Perform the set operations
4. Stop

Program:

L1 = {'Pitch', 'Syllabus', 'Script', 'Grammar', 'Sentences'};

L2 = {'Grammar', 'Syllabus', 'Context', 'Words', 'Phonetics'};

print("Union of L1 and L2 is ",L1 | L2)

print("Intersection of L1 and L2 is ",L1 & L2)

print("Difference of L1 and L2 is ",L1 - L2)

print("Symmetric difference of L1 and L2 is ",L1 ^ L2)

Output:

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

'Syllabus', 'Context'}

Intersection of L1 and L2 is {'Grammar', 'Syllabus'}

Difference of L1 and L2 is {'Script', 'Pitch', 'Sentences'}

Symmetric difference of L1 and L2 is {'Words', 'Context', 'Script', 'Pitch',

'Sentences', 'Phonetics'}

RESULT:

Thus the program and Output successful verified.

6. Implementing programs using Functions. (Factorial, largest number in a list, area of shape)

A) Program for Factorial of a number


Aim:
To write a python program for implementing a factorial of a given number using
recursion.

Algorithm:
Step 1 : Start
Step 2 :Read a number
Step 3 : Pass the number as an argument to a recursive factorial function.
Step 4 : Define the base condition as the number to be lesser than or equal to 1 and return 1 if
it is.
Step 5 : Otherwise call the function recursively with the number minus 1 multiplied by the
number itself.
Step 6 : Print the result.
Step 7: Stop.

Program :
def fact(n):
if n==1:
return n
else:
return n*fact(n-1)
num = int(input("Enter a number: "))
print("The factorial of",num,"is",fact(num))

Output:
Enter a number: 5
The factorial of 5 is 120

RESULT:

Thus the program and Output successful verified.


6.b Program to find the largest number in a list
Aim :
To write a program to find the largest number in a list using python.

Algorithm :
Step 1 : Start
Step 2 : Read number of elements to be store in a list
Step 3 : Initialize an empty list lst = [].
Step 4 : Read each number in your python program using a for loop.
Step 5 : In the for loop append each number to the list.
Step 6 : Define a custom function, which is an accepted number list and used to find
the largest number from list.
Step 7 : Call this custom function and store the function result.
Step 8 : Print the result.
Step 9 : Stop

Program :
def find_max( list ):
max = list[ 0 ]
for a in list:
if a > max:
max = a
return max
num = int(input('How many numbers: '))
lst = [] for n in range(num):
numbers = int(input('Enter number '))
lst.append(numbers)
print("Maximum element in the list is :",find_max(lst))

Output:
How many numbers: 5
Enter number 10
Enter number 20
Enter number 30
Enter number 40
Enter number 50
Maximum element in the list is : 50

RESULT:

Thus the program and Output successful verified.

6.c Program to find the area of different shapes


Aim :
To write a program to find the area of different shapes using python.
Algorithm :
Step 1 : Start.
Step 2 : Call the appropriate shapes and get the inputs.
Step 3 : Compute the formula as the shapes.
Step 4 : Return the area Step
5 : Print the area.
Step 6 : Stop
Program :
def cir():
r=int(input("Enter the radious"))
area=3.14*r*r
return area def tria():
b=int(input("Enter the base"))
h=int(input("Enter the height"))
area=1/2*b*h
return area def square():
a=int(input("Enter the side"))
area=a*a
return area def rect():
l=int(input("Enter the length"))
w=int(input("Enter the width"))
area=l*w
return area
print(cir())

print(tria())
print(square())
print(rect())

Output:

Enter the radious2


12.56
Enter the base12
Enter the height2
12.0
Enter the side3
9
Enter the length12
Enter the width8
96

RESULT:

Thus the program and Output successful verified.

7. Implementing programs using Strings. (reverse, palindrome, character count,


replacing characters)

7(a). REVERSE A STRING

AIM:

To implement python program using strings.

ALGORITHM:

STEP1: Get the input from the user


STEP2: The function call is invoked, where the string is passed as input to reverse function

STEP3: For loop is executed until the last character in the string is reached

STEP4: The str variable is incremented for each iteration and returned as the reversed string.

PROGRAM:

def reverse(s):

str = ""

for i in s:

str = i + str

return

strs =input("Enter the string to reverse:")

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

print (s)

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

print (reverse(s))

OUTPUT:

Enter the string to reverse:python

The original string is : python

The reversed string is : nohtyp

RESULT:

Thus the program and Output successful verified.

7(b). PALINDROME OF A STRING

AIM:
To implement python program using strings.

ALGORITHM:

STEP1: Get the input string from the user.

STEP2: Check whether string is equal to the reverse of the same string using slicing operation
in an if condition.

STEP3: If the condition is satisfied, then the string is a palindrome.

PROGRAM:

string=input(("Enter a letter:"))
if(string==string[::-1]):
print("The letter is a palindrome")
else:
print("The letter is not a palindrome")

OUTPUT:

Enter a letter: mom

The letter is a palindrome

RESULT:

Thus the program and Output successful verified.

7(c). CHARACTER COUNT

AIM:

To implement python program using strings.

ALGORITHM:

STEP1: Get the string from the user


STEP2: Get the character to be counted in the string from the user.

STEP3: For loop is executed until the last character is checked in the string

STEP4: Using the if condition, the character entered and the characters in the string is
compared inside the for loop for each iteration.

STEP5: The number of times the entered character has been present in the string will be
returned as the total count.

PROGRAM:

test_str = input("Enter the String:")

character=input("Enter the Character:")

count = 0

for i in test_str:

if i == character:

count = count + 1

print ("Count is : "+ str(count))

OUTPUT:

Enter the String: expression

Enter the Character: s

Count is : 2

RESULT:

Thus the program and Output successful verified.


7(d). REPLACING CHARACTERS

AIM:

To implement python program using strings.

ALGORITHM:

STEP1: Read the String

STEP2: Replace the character in the string using replace() method.

STEP3: Display the replaced string.

PROGRAM:

string = " HI! HI! HI! WELCOME TO PYTHON PROGRAMMING"

print ("Original String:",string)

replace1=string.replace("HI", "HELLO")

print ("Replaced String 1:",replace1)

replace2=replace1.replace("HELLO", "Hello", 3)

print ("Replaced String 2:",replace2)

OUTPUT:

Original String: HI! HI! HI! WELCOME TO PYTHON PROGRAMMING

Replaced String 1: HELLO! HELLO! HELLO! WELCOME TO PYTHON


PROGRAMMING

Replaced String 2: Hello! Hello! Hello! WELCOME TO PYTHON PROGRAMMING

RESULT:

Thus the program and Output successful verified.


8. Implementing programs using written modules and Python Standard Libraries (pandas,
numpy.
Matplotlib, scipy)

8(a) Simple Program using numpy

AIM:
To write a python program to plot a simple python graph for a straight line.

ALGORITHM:

1. Start the Program


2. Import the modules numpy, pyplot
3. Store the set of values in x, equation in y
4. Assign title, axis label for the graph
5. Show the graph
6. Stop

PROGRAM:
import numpy as np from
matplotlib import pyplot as plt
x = np.arange(1,11)
y=2*x+7
plt.title("Matplotlib demo")
plt.xlabel("x axis caption")
plt.ylabel("y axis caption")
plt.plot(x,y)
plt.show()
OUTPUT:

RESULT:

Thus the program and Output successful verified.

8.(b) Program using pandas


AIM:
To create data frames using pandas in python.

ALGORITHM:
1.Start the Program.
2. Import numpy and pandas
3. Create a dictionary with student name, marks of three subjects
4. Convert the dictionary to a data frame
5. Print the data frame
6. Stop

PROGRAM:
import numpy as np

import pandas as pd
mydictionary = {'names': ['Somu', 'Kiku', 'Amol', 'Lini'],

'physics': [68, 74, 77, 78],

'chemistry': [84, 56, 73, 69],

'algebra': [78, 88, 82, 87]}

#create dataframe using dictionary

df_marks = pd.DataFrame(mydictionary)

print(df_marks)

OUTPUT:
names physics chemistry algebra

0 Somu 68 84 78

1 Kiku 74 56 88

2 Amol 77 73 82

3 Lini 78 69 87

RESULT:

Thus the program and Output successful verified.

8(c) Using Scipy - Univariate Interpolation

AIM:
To implement a python Program to plot an univariate interpolation.

ALGORITHM:
1.Start
2. Import interpolate , pyplot
3. Using x, y values arrange the graph area
4. Using pyplot , print the graph
5. Stop

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

OUTPUT:

RESULT:

Thus the program and Output successful verified.


9.Implementing real-time/technical applications using File handling. (copy from one file to
another, word count, longest word)

9.A. Python program to copy the content of one file into another file

Aim :

To write a program to copy the content of one file into another file.

Algorithm:
Step 1: Start

Step 2: Open one file called test.txt in read mode.

Step 3: Open another file out.txt in write mode.

Step 4: Read each line from the input file and write it into the output file.

Step 5: Stop.
Program:

print("Enter the Name of Source File: ")

sourcefile = input()

print("Enter the Name of Target File: ")

targetfile = input()

fileHandle = open(sourcefile, "r")

texts = fileHandle.readlines()

fileHandle.close() f

ileHandle = open(targetfile, "w")

for s in texts:

fileHandle.write(s)

fileHandle.close()
print("File Copied Successfully!")

Output:

Enter the Name of Source File: in.txt

Enter the Name of Target File: out.txt

File Copied Successfully

RESULT:

Thus the program and Output successful verified.

B . Python Program to Count the Number of Words in a Text File

Aim :

To write a Python Program to Count the Number of Words in a Text File


Algorithm:
Step 1: Start

Step 2: Open file “book.txt” in read mode and store contents of file in file object say fin

Step 3: Read each line from the file using read() function
Step 4: Split the line to form a list of words using split() function and store it in variable

say l.

Step 5: Intitially Set the value of count_words variable to zero in which we will store the

calculated result.

Step 6: Use for loop to read list of word stored in variable say l.

Step 7: Find the length of words in the list and print it.

Step 8: Close the file using close()

Step 9: Stop
Program:

fin = open("book.txt","r")

str = fin.read()
l = str.split()

count_words = 0

for i in l:

count_words = count_words + 1

print(count_words) fin.close()

Output:

25

RESULT:

Thus the program and Output successful verified.

C . Python Program to Count the Number of Words in a Text File

Aim :

To write a Python Program to Count the Number of Words in a Text File

Algorithm:
Step 1: Start

Step 2: Open text file say ‘name.txt’ in read mode using open function

Step 3: Pass file name and access mode to open function

Step 4: Read the whole content of text file using read function and store it in another
variable say ‘str’
Step 5: Use split function on str object and store words in variable say ‘words’

Step 6: Find maximum word from words using len method

Step 7: Iterate through word by word using for loop

Step 8: Use if loop within for loop to check the maximum length of word
Step 9: Store maximum length of word in variable say ‘longest_word’

Step 10: Display longst_word using print function


Step 11: Stop

Program:

fin = open("name.txt","r")

str = fin.read()

words = str.split()

max_len = len(max(words, key=len))

for word in words:

iflen(word)==max_len:

longest_word=word

print(longest_word)

Output:

Encyclopedia

RESULT:

Thus the program and Output successful verified.

10.Implementing real-time/technical applications using Exception handling. (divide by zero


error, voter’s age validity, student mark range validation)

10(a). DIVIDE BY ZERO ERROR

AIM:
To implement python program for real-time / technical applications using Exception
handling.

ALGORITHM:

STEP1: Get the input for n, d and c.

STEP2: In the try block, calculate q=n/(d-c).

STEP3: If the denominator is non-zero, then the quotient gets printed.

STEP4: Otherwise, the exception Zero Division Error is executed.

PROGRAM:

n=int(input("Enter the value of n:"))

d=int(input("Enter the value of d:"))

c=int(input("Enter the value of c:")) try:

q=n/(d-c)

print("Quotient:",q) except

ZeroDivisionError:

print("Division by Zero!")

OUTPUT:

Enter the value of n: 10

Enter the value of d: 5

Enter the value of c: 5

Division by Zero!

RESULT:

Thus the program and Output successful verified.


10(b). VOTER’S AGE VALIDITY

AIM:

To implement python program for real-time / technical applications using Exception


handling.

ALGORITHM:

STEP1: Get the age from the user.

STEP2: In the if block, check if the age is greater than 18, then print “Eligible to vote”.

STEP3: Otherwise, print “Not eligible to vote”

STEP4: If the age entered is a non-number, then the exception block is executed.

PROGRAM:

def main():

try:

age=int(input("Enter your age"))

if age>18:

print("Eligible to vote")

else:

print("Not eligible to vote")

except: print("age must be a valid

number") main()

OUTPUT 1:

Enter your age 24

Eligible to vote

OUTPUT 2:
Enter your age 14

Not eligible to vote

RESULT:

Thus the program and Output successful verified.

10(c). STUDENT MARK RANGE VALIDATION

AIM:

To implement python program for real-time / technical applications using Exception


handling.

ALGORITHM:

STEP1: Get the number between the range(1 - 100)

STEP2: In the if block, check whether the number is between 1 to 100.

STEP3: Otherwise, print “Above 100, wrong”

STEP4: If the age entered is a non-number, then the exception block is executed.

PROGRAM:

def input_number(min,max):

try:

while True: n=int(input("Please enter a number between {} and {}

:".format(min,max)))

n=int(n)

if(min<=n<=max):

print(n)

break
else:

print("Above 100, wrong")

break

except:

print("mark must be a valid number") input_number(1,100)

OUTPUT 1:

Please enter a number between 1 and 100 :4

OUTPUT 2:

Please enter a number between 1 and 100 :156

Above 100, wrong

OUTPUT 3:

Please enter a number between 1 and 100 : ab mark

must be a valid number

RESULT:

Thus the program and Output successful verified.

11.Exploring Pygame tool.

AIM:
• 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.
• Pygame was officially written by Pete Shinners to replace PySDL.

• Pygame is suitable to create client-side applications that can be potentially


wrapped in a standalone executable.

Pygame Installation

Install pygame in Windows

Before installing Pygame, Python should be installed in the system, and it is good to have
3.6.1 or above version because it is much friendlier to beginners, and additionally runs faster.

There are mainly two ways to install Pygame, which are given below:

1. Installing through pip: The good way to install Pygame is with the pip tool. The
command is the following:

py -m pip install -U pygame --user

2. Installing through an IDE: The second way is to install it through an IDE and here we
are using Pycharm IDE. Installation of pygame in the pycharm is straightforward. We can
install it by running the above command in the terminal or use the following steps:

Open the File tab and click on the Settings option.

Select the Project Interpreter and click on the + icon.

It will display the search box. Search the pygame and click on the install package button.
To check whether the pygame is properly installed or not, in the IDLE interpreter, type the
following command and press Enter:

import pygame

If the command runs successfully without throwing any errors, it means we have successfully
installed Pygame and found the correct version of IDLE to use for pygame programming.

Example

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

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.

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.

Pygame Surface

The pygame Surface is used to display any image. The Surface has a pre-defined resolution
and pixel format. The Surface color is by default black. Its size is defined by passing the size
argument.
Pygame Clock

Times are represented in millisecond (1/1000 seconds) in pygame. Pygame clock is used to
track the time. The time is essential to create motion, play a sound, or, react to any event.

12.Developing a game activity using Pygame like bouncing ball, car race etc.

12. A. Bouncing ball game

Aim:

Write a python program to simulate bouncing ball using pygame

Algorithm:

1. Import pygamemodule

2. Call pygame.init() to initiate all imported pygamemodule

3. Set the screen size in terms of pixels using


pygame.display.set_mode((400,300)

4. If there is any event in pygamequeue

a. Get the event from the pygamequeue

b. If event types is pygame.QUIT then setdone=true

5. Else, Draw the circle update the screen display with new circle to bring
bouncingeffect

6. Call sys.exit() to uninitialized all the pygamemodules

Program:

import pygame
from pygame.locals
import * pygame.init()
screen = pygame.display.set_mode((40
0, 300))
done = False while not
done:
for event in pygame.event.get():
if event.type ==
pygame.QUI

T: done =
True pygame.draw.circle(screen,
(255,255,255), [100, 80], 10,
0)
pygame.display.update()
pygame.draw.circle(screen, (0,0,0), [100, 80],
10, 0)
pygame.display.update()
pygame.draw.circle(screen, (255,255,255), [150, 95], 10,
0)
pygame.display.update()
pygame.draw.circle(screen, (0,0,0), [150, 95], 10, 0)
pygame.display.update()
pygame.draw.circle(screen, (255,255,255), [200, 130], 10, 0)
pygame.display.update()pygame.draw.circle(screen, (0,0,0),
[200, 130], 10, 0)
pygame.display.update()
pygame.draw.circle(screen, (255,255,255), [250, 150], 10, 0)
pygame.display.update()
pygame.display.update()
for event in
pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
Output:

RESULT:

Thus the program and Output successful verified.

12. B. Car Game

Aim:

Write a python program to simulate car game using pygame.

Algorithm:

1. Import pygamemodule

2. Call pygame.init() to initiate all imported pygamemodule

3. Set the screen size in terms of pixels using


pygame.display.set_mode((798,600

4. Set the logo and the background for the game.


5. Assign the car images for the race and set its parameters

6. Set the key movement values

7. Update the screen display after every change in car position

8. Call the game loop until run

9. Stop

Program:

import pygame pygame.init()

from pygame.locals import*

import random screen =

pygame.display.set_mode((798,600))

pygame.display.set_caption('Racing Beast')

logo = pygame.image.load('car game/logo.jpeg')

pygame.display.set_icon(logo)

def gameloop():

bg = pygame.image.load('car game/bg.png')

maincar = pygame.image.load('car game\car.png')

maincarX = 350

maincarY = 495

maincarX_change = 0

maincarY_change = 0
car1 = pygame.image.load('car game\car1.jpeg')

car1X = random.randint(178,490)

car1Y = 100

car2 = pygame.image.load('car game\car2.png')

car2X = random.randint(178,490)

car2Y = 100

car3 = pygame.image.load('car game\car3.png')

car3X = random.randint(178,490)

car3Y = 100

run = True

while run:

for event in pygame.event.get(): if

event.type == pygame.

QUIT:

run = False

if event.type == pygame.KEYDOWN:

if event.key == pygame.K_

RIGHT:

maincarX_change += 5

if event.key == pygame.K_

LEFT:

maincarX_change -= 5

if event.key == pygame.K_

UP:
maincarY_change -= 5

if event.key == pygame.K_

DOWN:

maincarY_change += 5

if event.type == pygame.

KEYUP:

if event.key == pygame.K_

RIGHT:

maincarX_change = 0

if event.key == pygame.K_

LEFT:

maincarX_change = 0

if event.key == pygame.K_

UP:

maincarY_change = 0

if event.key == pygame.K_DOWN:

maincarY_change = 0

if maincarX< 178:

maincarX = 178

if maincarX> 490:

maincarX = 490

if maincarY< 0:

maincarY = 0
if

maincarY> 495:

maincarY = 495

screen.fill((0,0,0))

#displaying the

background image

screen.blit(bg,(0,0))

#displaying our main

car

screen.blit(maincar,(ma

incarX,maincarY))

#displaing other cars

screen.blit(car1,(car1X,car1Y))

screen.blit(car2,(car2X,car2Y))

screen.blit(car3,(car3X,car3Y))

#updating the values maincarX

+= maincarX_change maincarY

+=maincarY_change

car1Y += 10

car2Y += 10

car3Y += 10

if car1Y > 670:

car1Y = -100

if car2Y > 670:

car2Y = -150
if car3Y > 670:

car3Y = -200

pygame.display.upda

te() gameloop()

Output:

RESULT:

Thus the program and Output successful verified.

You might also like