Lab Manual
Lab Manual
04 Implementing real-time/technical
applications using Lists, Tuples.
05 Implementing real-time/technical
applications using Sets,
Dictionaries.
09 Implementing real-time/technical
applications using File handling.
10 Implementing real-time/technical
applications using Exception
handling.
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.)
Aim :
To draw the flowchart for Electricity bill calculation with the following rates for its
customers: -
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:
Aim :
Algorithm :
Step 1: Start
RESULT:
Aim :
Algorithm :
Step 1: Take in the value of x in degrees and the number of terms and store it in separate
variables.
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 6: Stop
Flowchart:
RESULT:
Aim :
Algorithm :
Step 1: Start
5: Stop
Flowchart:
START
READ D,L
COMPUTE W= D**2*L/162
DISPLAY W
STOP
RESULT:
Aim :
Algorithm :
Step 1: Start
Step 4: Print w
Step 5: Stop
Flowchart:
START
READ
LBS
COMPUTE
W=LBS/2.2046
DISPLAY
W
STOP
RESULT:
Aim :
Algorithm :
Step 1: Start
Step 5: Stop
Flowchart:
START
READ KVA,
Voltage
DISPLAY
Current
STOP
RESULT:
Aim:
Algorithm:
STEP 4: temp = P
STEP 5: PRINT P, Q
Program:
temp= P
P=Q
swapping: ", P)
RESULT:
Aim:
Algorithm:
STEP 5: Stop
Program:
list=[10,20,30,40,50]
n=2
print(list[n:]+list[:n])
Output:
RESULT:
Aim:
Algorithm:
STEP 6: Stop
Program:
p2 = [6, 6]
print(distance)
Output:
6.324555320336759
RESULT:
3.Scientific problems using Conditionals and Iterative loops. (Number series, Number
Patterns, pyramid pattern)
Aim:
Algorithm:
Step 2: Read the three integer values in num1, num2, and num3.
5: Stop
Program:
largest = num1
largest = num2
else:
largest = num3
Output:
RESULT:
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 6: Stop
Program:
n=int(input("Enter a number:"))
tot=0
while(n>0):
dig=n%10
tot=tot+dig
n=n//10
Output:
Enter a number:456
RESULT:
Aim:
Algorithm:
Step 1: Start
Step 2: Read n
4: for i=1 to n do
if(n%i)==0, then
s=s+i
Step 7: Stop
Program:
Sum = 0
if(Number % i == 0):
else:
6 is a Perfect Number
RESULT:
Aim:
Algorithm:
Step 1: Start
Step 4: Enter the number of terms of Fibonacci series to be printed Step 5: Print First two
terms of series
-> sum=t1+t3
-> t1=t2
-> t2=sum
Step 7: Stop
Program:
t1 = 0
t2 = 1
sum = 0
count = 1
count += 1
t1 = t2
t2 = sum
sum = t1 + t2
Output:
Fibonacci Series:
0112358
RESULT:
Aim:
Algorithm:
STEP 3: Stop
Program 1:
print(end=" ")
print()
Output:
*
**
***
****
*****
Program 2:
k=1
for i in range(0, num_rows):
k=k+1
print()
Output:
**
***
****
*****
Program 3:
k=8
k = k - 2 for j in
range(0, i+1):
print("* ", end="")
print()
Output:
* *
* **
* ***
* ****
Program 4:
for i in range(num_rows,0,-1):
print(end=" ")
for j in range(0,i):
print()
Output:
* * * * *
* * * *
* * *
* *
Program 5:
rows = 6
for i in range(rows):
for j in range(i):
print('')
Output:
222
3 323
4 4 426
5 5 5 526
RESULT:
3 (f ) Pascals Triangle
Aim:
Algorithm:
STEP 1: Read the number of rows to be printed
STEP 4: Stop
Program:
C=1
C = C * (i - j) // j
print()
Output:
11
121
1331
14641
RESULT:
Aim:
Algorithm:
STEP 3: Stop
Program 1:
# 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:
for i in range(0,len(str)):
for j in range(0,i+1):
print(str[j],end="")
print()
Output:
Aj
Aji Ajin
program4
for i in range(n):
# printing spaces
for j in range(i):
# printing alphabet
for j in range(2*(n-i)-1):
print()
Output:
ABCDEFGHI
ABCDEFG
ABCDE
ABC
A
Program 5:
n=5
# upward pyramid
for i in range(n):
print()
Output:
A
ABC
ABCDE
ABCDEFG
ABCDEFGHI
ABCDEFG
ABCDE
ABC
A
RESULT:
Aim:
Algorithm:
Step 1: Start
Step 3: Using a for loop, iterate on all the numbers in the range
Else skip
Step 6 : Stop
Program:
if num> 1:
if (num % i) == 0:
break
else:
print(num)
Output:
907
911
919
929
937
941
947
953
967
971
977
983
991
997
RESULT:
Aim:
Algorithm:
Step 1: Start
Step4 : If the choice is 1, read the book name from the user and append to list
Step 6: Stop
Program:
my_book=[]
ch='y'
while(ch=='y'):
print('''
2. Display Books
''')
if(choice==1):
my_book.
append(book)
elif(choice==2):
for i in my_book:
print(i)
else:
print("Invalid choice!")
print("Bye!")
Output:
Display Books
Enter choice: 1
RESULT:
Aim:
Algorithm:
Step 1: Start
Step 2: Create a list of components of automobile
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('''
3. Total Components
''')
if(choice==1):
print(components)
elif(choice==2):
print("The components are:")
print(components+components1)
elif(choice==3):
print("Main Components:",len(components))
print("Other Components:",len(components1))
elif(choice==4):
components.sort()
print("MainComponents:",components)
print("Sorted order")
else:
print("Invalid choice!")
print("Bye!")
Output:
3. Total Components
Enter choice: 4
RESULT:
Aim:
Algorithm:
Step 1: Start
Step 9: Stop
Program:
'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
''')
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!")
print("Bye!")
Output:
1. Display Materials
Enter choice: 4
15
1. Display Materials
Enter choice: 5
Bricks
RESULT:
Aim:
Algorithm:
Step 1: Start
Step 4: Stop
Program:
print(numbers[0]) print(numbers[5])
print(numbers[1]) print(numbers[-1])
print(numbers[-3]) print(numbers[-4])
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)
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']
['bye']
['hello', 'world', 100, 100, 'bye', 99, 11, 22] ['hello', 11, 22, 33, 'bye', 99, 11, 22]
[]
RESULT:
Aim:
Algorithm:
Step 1: Start
Type, del, sum, max, min, sorted, packing, slicing, indexing, membership Step 4:
Stop
Program:
print(tuple1[0])
print(tuple1[4][1])
print(tuple1[-1]) print(tuple1[2:5])
Tuple1 = (1, 3, 4)
print (1 in Tuple1)
print(5inTuple1)
print(max(Tuple1))
print(sum(Tuple1))
print(sorted(Tuple1))
print(name)
print(height)
print(profession)
Output:
(1, 3, 4, 5, 'test')
ax
True
False
[1, 3, 4]
Sai
5 ft
Actor
RESULT:
AIM:
To write a python program for to add ,remove and pop the automobile components using
python set operations.
ALGORITHM:
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:
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:
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
})
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:
Aim:
ALGORITHM:
Program:
Output:
'Syllabus', 'Context'}
'Sentences', 'Phonetics'}
RESULT:
6. Implementing programs using Functions. (Factorial, largest number in a list, area of shape)
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:
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:
print(tria())
print(square())
print(rect())
Output:
RESULT:
AIM:
ALGORITHM:
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
print (s)
print (reverse(s))
OUTPUT:
RESULT:
AIM:
To implement python program using strings.
ALGORITHM:
STEP2: Check whether string is equal to the reverse of the same string using slicing operation
in an if condition.
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:
RESULT:
AIM:
ALGORITHM:
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:
count = 0
for i in test_str:
if i == character:
count = count + 1
OUTPUT:
Count is : 2
RESULT:
AIM:
ALGORITHM:
PROGRAM:
replace1=string.replace("HI", "HELLO")
replace2=replace1.replace("HELLO", "Hello", 3)
OUTPUT:
RESULT:
AIM:
To write a python program to plot a simple python graph for a straight line.
ALGORITHM:
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:
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'],
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:
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:
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 4: Read each line from the input file and write it into the output file.
Step 5: Stop.
Program:
sourcefile = input()
targetfile = input()
texts = fileHandle.readlines()
fileHandle.close() f
for s in texts:
fileHandle.write(s)
fileHandle.close()
print("File Copied Successfully!")
Output:
RESULT:
Aim :
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 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:
Aim :
Algorithm:
Step 1: Start
Step 2: Open text file say ‘name.txt’ in read mode using 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 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’
Program:
fin = open("name.txt","r")
str = fin.read()
words = str.split()
iflen(word)==max_len:
longest_word=word
print(longest_word)
Output:
Encyclopedia
RESULT:
AIM:
To implement python program for real-time / technical applications using Exception
handling.
ALGORITHM:
PROGRAM:
q=n/(d-c)
print("Quotient:",q) except
ZeroDivisionError:
print("Division by Zero!")
OUTPUT:
Division by Zero!
RESULT:
AIM:
ALGORITHM:
STEP2: In the if block, check if the age is greater than 18, then print “Eligible to vote”.
STEP4: If the age entered is a non-number, then the exception block is executed.
PROGRAM:
def main():
try:
if age>18:
print("Eligible to vote")
else:
number") main()
OUTPUT 1:
Eligible to vote
OUTPUT 2:
Enter your age 14
RESULT:
AIM:
ALGORITHM:
STEP4: If the age entered is a non-number, then the exception block is executed.
PROGRAM:
def input_number(min,max):
try:
:".format(min,max)))
n=int(n)
if(min<=n<=max):
print(n)
break
else:
break
except:
OUTPUT 1:
OUTPUT 2:
OUTPUT 3:
RESULT:
AIM:
• Pygame is a cross-platform set of Python modules which is used to create
video games.
Pygame Installation
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:
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:
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
screen = pygame.
display.set_mode((400,500))
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.QUIT - This is used to terminate the event when we click on the close button at the
corner of the window.
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.
Aim:
Algorithm:
1. Import pygamemodule
5. Else, Draw the circle update the screen display with new circle to bring
bouncingeffect
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:
Aim:
Algorithm:
1. Import pygamemodule
9. Stop
Program:
pygame.display.set_mode((798,600))
pygame.display.set_caption('Racing Beast')
pygame.display.set_icon(logo)
def gameloop():
bg = pygame.image.load('car game/bg.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
car2X = random.randint(178,490)
car2Y = 100
car3X = random.randint(178,490)
car3Y = 100
run = True
while run:
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))
car
screen.blit(maincar,(ma
incarX,maincarY))
screen.blit(car1,(car1X,car1Y))
screen.blit(car2,(car2X,car2Y))
screen.blit(car3,(car3X,car3Y))
+= maincarX_change maincarY
+=maincarY_change
car1Y += 10
car2Y += 10
car3Y += 10
car1Y = -100
car2Y = -150
if car3Y > 670:
car3Y = -200
pygame.display.upda
te() gameloop()
Output:
RESULT: