Ge3151 Python Lab Manual
Ge3151 Python Lab Manual
LAB MANUAL
REGULATION 2021
GE3171 PSPP
LABORATORY
Year / Semester: I / I
INDEX
Week- [Link] List of Programs [Link] Date Sign
No
1 1. Identification and solving of simple real
life or scientific or technical problems, and
developing
flow charts for the same.
a) Electricity Billing,
b) Retail shop billing,
c) Sin series
d) Weight of amotorbike,
e) Weight of a steel bar,
f) Compute Electrical Current in Three
Phase AC Circuit, etc.)
2 Python programming using simple
statements and expressions
a) Exchange the values of two variables
b) Circulate the values of n variables
c) Distance between two points
3 Scientific problems using Conditionals and
Iterative loops.
a) Number series,
b) Number Patterns
c) Pyramid pattern
4 Implementing real-time/technical
applications using Lists, Tuples.
a) Items present in a library
b) Components of a car
c) Materials required for construction of a
building operations of list & tuples)
5 Implementing real-time/technical applications
using Sets, Dictionaries.
a) Language, components of an automobile,
b) Palindrome
c) Character count,
d) Replacingcharactersx`
8 Implementing programs using written
modules and Python Standard Libraries
a) Pandas
b)Numpy
c) Matplotlib
d)Scipy
9 Implementing real-time/technical
applications using File handling.
a) copy from one file to another
b) Word count
c) Longest word
10 Implementing real-time/technical
applications using Exception handling.
a) Divide by zero error
b)Voter‟s age validity
c) Student mark range validation
11 Exploring Pygame tool
12 Developing a game activity using Pygame
like a) bouncing ball
b) Car race
ELECTRICITY BILLING
ecord Notes
DATE:
AIM
To write an algorithm and flowchart to solve compute Electricity billing.
Ac circuit.
FLOWCHART
RESULT
Thus an algorithm and flowchart for electricity billing has been produced successfully.
EX NO:1B
AIM
ALGORITHM
Step1: Start
Step2: Update the list of items purchased on database
[Link] shopping complete means calculate total
Step4: If shopping not completed purchase remaining items
Step4: Cash payment is done after calculating the total amount
Step5: Stop
FLOWCHART
Start
Purchase Items
No
Yes After
Shoppin gyes
Calculate total
Cash payment
Stop
RESULT
Thus an algorithm and flowchart for retail shop billing has been produced successfully.
EX NO:1C
SINE SERIES
DATE:
AIM
ALGORITHM
Step 1:Start
Step 2: Read x,n
Step 3:Calculatex=x*3.14159/180
Step 4: t=x
Step 5 : Sum=x
Step 6: Check condition using While i<=n
Step 7: t=t*(-1)*x*x)/(2*i*2i+1))
Step 8 : sum=sum+t
Step 9 :i=i+1
Step 7: Print y,sum
Step 3: Stop
FLOWCHART
RESULT
Thus an algorithm and flowchart for sinseries has been produced successfully.
EX NO:1D
AIM
ALGORITHM
Step 1:Start
Step 2:Heigt=Input "Height in Feet"
Step 3:Weight=Input "weight in Kilogram"
Step 4:x=(Weight/Height*Height)
Step 5:Print "Motor bike weight"-->x
Step 6:Stop
FLOWCHART
Start
yes
x=(Weight/Height*Height)
Stop
RESULT
Thus an algorithm and flowchart for weight of motor bike has been produced successfully.
EX NO:1E
AIM
ALGORITHM
Step1:start
Step2:Read the variables Diameter and length need to calculate the weight.
Step5:stop
FLOWCHART
Start
W=D^2*L/162
PRINT WEIGHT
STOP
RESULT
Thus an algorithm and flowchart for above program has been produced successfully.
EX NO:1F
AIM
To write an algorithm and flowchart to solve simple real life problems for electric current three phase
Ac circuit.
ALGORITHM
Step1: Start
Step2: Read the variables P,V and PF values
Step3: Assign the values to variables
Step4: Compute the electric current for three phase AC circuit using
Formula : I = P/(V * PF * 1.73)
Step5: print the electric current I Value
Step 6: Stop
FLOWCHART
start
I= P/(V * PF * 1.73)
Print I
stop
RESULT
Thus an algorithm and flowchart for above program has been produced successfully.
EX NO:2A
EXCHANGE OF TWO VALUES
DATE:
AIM
ALGORITHM
Step1: Start
Step2: Read the variables x,y
Step3: Assign the values to variables
Step4: Perform swapping operations
Step5: print the value of after swapping
Step 6: Stop
PROGRAM
x=5
y=10
temp=x
x=y
y=temp
print('The value of x after swapping:',x)
print('The value of y after swapping:',y)
OUTPUT
RESULT
Thus the exchange of two values has been executed and verified successfully.
EX NO:2B
CIRCULATE THE VALUE OF N VARIABLES
DATE:
AIM
ALGORITHM
Step1: Start
Step2: Read the variables x,y
Step3: Assign the values to variables
Step4: Perform swapping operations
Step5: print the value of after swapping
Step 6: Stop
PROGRAM
no_of_terms = int(input("Enter number of values : "))
list1 = []
forval in range(0,no_of_terms,1):
[Link](ele)
forval in range(0,no_of_terms,1):
ele = [Link](0)
[Link](ele)
print(list1)
OUTPUT
Enter number of values : 3
Enter integer : 6
Enter integer : 7
Enter integer : 8
[7, 8, 6]
[8, 6, 7]
[6, 7, 8]
RESULT
Thus the program for circulate the value of n variables has been executed and verified successfully
EX NO:2C
DISTANCE BETWEEN TWO POINTS
DATE:
AIM
ALGORITHM
PROGRAM
x1=int(input("enter x1 : "))
x2=int(input("enter x2 : "))
y1=int(input("enter y1 : "))
y2=int(input("enter y2 : "))
result= ((((x2 - x1 )**2) + ((y2-y1)**2) )**0.5)
print("distance between",(x1,x2),"and",(y1,y2),"is : ",result)
OUTPUT
enter x1 : 4
enter x2 : 6
enter y1 : 0
enter y2 : 6
distance between (4, 6) and (0, 6) is : 6.324555320336759
RESULT
Thus the program for distance between two points has been verified successfully.
EX NO:3A
NUMBER SERIES
DATE:
AIM
ALGORITHM
PROGRAM
print()
OUTPUT
Enter a number: 6
1 + 2 + 3 + 4 + 5 + 6 = 21
RESULT
Thus the program for number series has been verified successfully
EX NO:3B
NUMBER PATTERN
DATE:
AIM
ALGORITHM
Step1: Start
Step5:Stop.
PROGRAM
for i in range(5):
for j in range(5):
print(j+1, end=' ')
print()
OUTPUT
12345
12345
12345
12345
12345
RESULT
Thus the program for number pattern has been verified successfully.
EX NO:3C
PYRAMID PATTERN
DATE:
AIM
ALGORITHM
Step1: Start
Step2: Using two for loops print the number pattern in pyramid structure.
Step3: For loop is used to print numbers upto 2*i+1 values.
Step4: Print the numbers upto k+1 till end
Step5:Stop.
PROGRAM
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
1
123
12345
1234567
123456789
RESULT
Thus the program for pyramid pattern has been verified successfully
EX NO:4A
IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS USING LISTS
ITEMS PRESENT IN ALIBRARY
DATE:
AIM
To write a python program items present in library using list .
PROGRAM
list=["phy","che","mat","eng","tam"]
for i in range(0,4,1):
print(list[i])
[Link](3,"computer")
print(list)
print("computer" not in list)
[Link]("eng")
print(list)
print([Link]("mat"))
print([Link]("eng"))
print("tam" in list)
OUTPUT
phy
che
mat
eng
['phy', 'che', 'mat', 'computer', 'eng', 'tam']
False
['phy', 'che', 'mat', 'computer', 'tam']
2
0
True
RESULT
Thus the program for List items present in the Library has been verified successfully.
EX NO:4B
COMPONENTS OF A CAR
DATE:
AIM
To write a python program Components of a car using List .
PROGRAM
car_components=["Engine","battery","light","frontaxle","brakes"]
print(car_components)
car_components.insert(4,"radiator")
car_components.insert(3,"alternator")
print(car_components)
car_components.append("trunk")
car_components.append("air filter")
print(car_components)
car_components.pop(1)
print(car_components)
print(car_components[:-4])
car_components.extend("seat","windowframe","mirror")
print(car_components)
OUTPUT
print(len(materials))
print(len(material2))
print(max(materials))
print(min(materials))
print(cmp(materials,material2))
Output
RESULT:
Thus the Components of a car has been executed and verified successfully
EX NO:4C
CONSTRUCTION FOR BUILDING
DATE:
AIM
To write a python program items present in library using list .
PROGRAM
materials=("Cement bags","sand","aggregates","bricks")
material2=("steel bars","paint")
print(materials)
mat3 = (materials+material2)
print(mat3)
print(materials[:3])
print(material2[1])
print(len(materials))
print(len(material2))
print(max(materials))
print(min(materials))
print(cmp(materials,material2))
OUTPUT
RESULT:
Thus the Construction of a building has been executed and verified successfully
EX NO:5A
LANGUAGES
DATE:
AIM
To write a python program Languages using dictionary.
PROGRAM
language1={"tamil","english","telgu"}
language2={"hindi","urudu","malayalam","telgu"}
print(language1)
print(language2)
[Link]("spanish")
print(language1)
[Link]("kanada")
print(language2)
print(language1&language2)
print(language1|language2)
lang3=[Link](language2)
print(lang3)
OUTPUT
set(['tamil', 'telgu', 'english'])
set(['malayalam', 'hindi', 'urudu', 'telgu'])
set(['spanish', 'tamil', 'telgu', 'english'])
set(['malayalam', 'kanada', 'hindi', 'urudu', 'telgu'])
set(['telgu'])
set(['urudu', 'telgu', 'kanada', 'spanish', 'hindi', 'english', 'malayalam', 'tamil'])
set(['english', 'tamil', 'spanish'])
RESULT:
EX NO:5B
COMPONENTS OF AUTOMOBILE
DATE:
AIM
PROGARAM
com1={"steering wheel","gear","tyre","radiator"}
com2={"sensor","wheel","brake"}
print(com1)
print(com2)
print(com1|com2)
com3=[Link](com2)
[Link]("light")
print(com2)
OUTPUT
RESULT:
Thus the Components of Automobile has been executed and verified successfully
EX NO:5C
ELEMENTS OF A CIVIL STRUCTURE
DATE:
AIM
PROGRAM
ele1={1:"foundation",2:"floor"}
ele2={1:"walls",2:"beams",3:"roof",4:"stair"}
print(ele1)
print(ele2)
print(ele1[1])
print(ele2[3])
print([Link](2))
ele1[2]="cement"
print(ele1)
print([Link](2))
OUTPUT
RESULT:
Thus the Elements of a Civil structurehas been executed and verified successfully
EX NO:6A FACTORIAL
DATE
AIM
ALGORITHM
Step1: Start
Step2: Use factorial function to calculate the value.
Step3:If n==1 and n==0 return 1.
Step4:Get the value of num to print the values of factorial.
Step4:Call the factorial function.
Step5:Stop
PROGRAM
def factorial(n):
# Driver Code
num = 5;
print("Factorial of",num,"is",
factorial(num))
OUTPUT
Factorial of 5 is 120
RESULT
Thus the Factorial program has been executed and verified successfully
EX NO:6B
AIM
PROGRAM
#list
list=[3, 9, 7, 3, 6, 5, 7, 24, 6]
print("largest in ",list,"is")
print(largest(list))
OUTPUT
RESULT
Thus the program for largest number in list has been verified successfully.
EX NO:6C
AREA OF SHAPE
DATE
AIM
PROGRAM
deffindArea(r):
PI = 3.142
return PI * (r*r);
# Driver method
num=float(input("Enter r value:"))
print("Area is %.6f" % findArea(num));
OUTPUT
Enter r value:5
Area is 78.550000
RESULT
Thus the program for area of shape has been verified successfully.
EX NO:7A
STRING REVERSE
DATE:
AIM
PROGRAM
defreverse(s):
str=""
fori ins:
str=i +str
returnstr
s ="Pavithra"
OUTPUT
RESULT
Thus the program for string reverse has been verified successfully.
EX NO:7B
STRING PALINDROME
DATE:
AIM
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:COMPUTER
The letter is not a palindrome
Enter a letter:MALAYALAM
The letter is a palindrome
RESULT
Thus the program for string palindrome has been verified successfully.
EX NO:7C
AIM
PROGRAM
# using split()
# to count words in string
res =len(test_string.split())
# printing result
print("The number of words in string are : "+str(res))
print("The number of words in string are : ", len(test_string))
OUTPUT
RESULT
Thus the program for count the characters in string has been verified successfully.
EX NO:7D
REPLACE CHARACTERS
DATE:
AIM
PROGRAM
input_string = "This is [Link]. Here, you can read python tutorials for free."
new_string = input_string.replace('i', "I")
print("The original string is:")
print(input_string)
print("Output String is:")
print(new_string)
OUTPUT
RESULT
Thus the program for replace characters in string has been verified successfully.
EX NO:8A
PANDAS
DATE:
AIM
PROGRAM
import pandas as pd
df = [Link]({'X':[78,85,96,80,86], 'Y':[84,94,89,83,86],'Z':[86,97,96,72,83]});
print(df)
OUTPUT
X Y Z
0 78 84 86
1 85 94 97
2 96 89 96
3 80 83 72
4 86 86 83
RESULT
EX NO:8B
NUMPY
DATE:
AIM
PROGRAM
importnumpy as np
print(a)
#Slicing in array
print([Link])
b = a[1:, 2:]
print(b)
OUTPUT
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
(3, 4)
[[ 7 8]
[11 12]]
RESULT
EX NO:8C
MATPLOT
DATE:
AIM
PROGRAM
[Link] as plt
# Data is plotted:
[Link]('equal')
[Link]('Pie Plot')
[Link]()
OUTPUT
RESULT
EX NO:8D
SCIPY
DATE:
AIM
PROGRAM
defeqn(x):
return x + cos(x)
myroot = root(eqn, 0)
print(myroot.x)
OUTPUT
[-0.73908513]
RESULT
AIM
To write a python program for copy the contents of one file to another file.
ALGORITHM
Step1: Start
Step2: Read the existing file.
Step3: Copy the contents of file from first file to second file by using write keyword.
Step4: View the contents of second file.
Step5: Stop
PROGRAM
print("Enter the Name of Source File: ")
sFile = input()
print("Enter the Name of Target File: ")
tFile = input()
OUTPUT
RESULT
AIM
ALGORITHM
Step1: Start
Step2: Open the existing file to read in read mode.
Step3: Split the lines in a file using split( ) method.
Step4: Calculate the number of words in a file by performing,
number_of_words += len(lines)
PROGRAM
number_of_words = 0
OUTPUT
RESULT
Thus, the python program to count the words in file has been created and executed
successfully.
AIM
To write a python program to find the longest word in a file.
ALGORITHM
Step1: Start.
Step2: Open the existing file to read the contents of file.
Step3: The words in the lines are splitted using function split( ).
Step4: Maximum length of word in each line will be calculated,
max_len=len(max(words, key=len))
Step5: Check the length of word is equal to maximum length,
deflongest_word(filename):
withopen(filename,'r')asinfile:
words=[Link]().split()
max_len=len(max(words, key=len))
return[word for word in words iflen(word)==max_len]
print(longest_word('[Link]'))
OUTPUT
['[Link].']
RESULT:
Thus the Longest word in a file has been executed and verified successfully.
AIM
ALGORITHM
Step1: Start.
Step2: Get the two values by using variables num1 and num2.
Step3: Calculate the result by performing division operation.
Result= num1/num2
Step4: Print the result.
Step5: Otherwise if any invalid input print “Input Please Input Integer..."
Step6: If any value is divided by zero it throws zero division error.
Step7: Stop.
PROGRAM
try:
num1 = int(input("Enter First Number: "))
num2 = int(input("Enter Second Number: "))
print(result)
exceptValueError as e:
print("Invalid Input Please Input Integer...")
exceptZeroDivisionError as e:
print(e)
OUTPUT
Enter First Number: 45
Enter Second Number: 0
division by zero
RESULT
Thus the python program for exception handling to perform divide by zero
has been created and executed successfully.
DATE:
AIM
To write a python program for check the Voters age validity.
ALGORITHM
Step1: Start
Step2: Get the value of age.
Step3: Check if age is greater than 18.
Step4: Print eligible to vote.
Step5: Otherwise print not eligible to vote.
Step6: If any error occur means print an error occurred.
Step7: Stop
PROGRAM
def main():
try:
age=int(input("Enter your age"))
if age>18:
print("Eligible to vote")
else:
print("Not eligible to vote")
#display exception's default error message
exceptValueError as err:
print(err)
except:
print("An Error occured")
print("rest of the code...")
main()
OUTPUT
rest of the code...
Enter your ageTHIRTY
> THIRTY
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RESULT
Thus the python program to check the Voters age validity has been
EX:NO: 10C
IMPLEMETING REAL TIME APPLICATION USING EXCEPTION HANDLING
STUDENT MARK RANGE VALIDATION
DATE:
AIM
To write a python program to check the validation of student marks using exception
handling.
ALGORITHM
Step1: Start.
Step2: Read the values of s1,s2,s3,s4.
Step3: Calculate total and average using formula,
avg=(s1+s2+s3+s4)/4
Step4: Check if average greater than 50 print pass.
Step5: Otherwise print fail.
Step6: If any error occur means print value error.
Step7: Stop.
ROGRAM
s1=int(input("enter s1"))
s2=int(input("enter s2"))
s3= int(input("enter s3"))
s4=int(input("enter s4"))
avg=(s1+s2+s3+s4)/4
try:
if(avg>50):
print("pass")
else:
print("fail")
except:
print("valueerror")
OUTPUT
enter s18
enter s20
enter s37
enter s48.9
Traceback (most recent call last):
File "<string>", line 4, in <module>
ValueError: invalid literal for int() with base 10: '8.9'
RESULT
Thus the python program for student mark validation has been created and executed successfully.
EX:NO: 11
EXPLORING PYGAME TOOL
DATE:
AIM
To develop the games using python installation package by exploring Pygame tool.
PYGAME
Pygame is a set of Python modules designed to make games. It uses SDL which is a
cross-platform library that abstracts the multimedia components of a computer as audio and
video and allows an easier development of programs that uses this resources.
INSTALLATION
Before starting the installation process you must have python installed at your system. In
case you don‟t have it check this installation guide first.
The pygame installation itself can be different from an OS and can be checked for more
details at its [official install guide]
([Link] Installation).
But, to install it into a Debian based system such as Ubuntu you must first make sure its
dependencies are installed:
$ sudo apt-get build-dep python-pygame
Hello World
As usual, when we are learning something new in programming we start as small as possible to
check it everything is working properly before proceeding with the studies.
To make that let‟s create a file called [Link] with the following content:
import time
importpygame
[Link]()
[Link].set_caption('Hello World')
[Link]([0, 0, 0])
[Link]()
[Link](5)
Then we just need to run it:
$ python [Link]
So the result will be this:
The three first lines are common to the most programs written in python. At the first line,
we define the file encoding used by the python interpreter which was utf-8. This line is most
common at codes written in python 2 that has non ASCII characters, if you are using python 3
you probably won‟t use it because utf-8 is the default encoding already. The second and third
code lines are importing the python libraries that will be responsible for all the magic.
The command [Link]() starts all modules that need initialization inside pygame.
With the window created we can use the command fill from screen to fill it with the black
color. The colors are passed on a list of three elements that represent the values from RGB. Each
value can go from 0 to 255. You can change the values to see by yourself the window changing
its color.
RESULT
Thus the Pygame tool for development of gaming application using python has been
explored and developed successfully.
EX NO:12 A
DEVELOPING A GAME ACTIVITY USING PYGAME LIKE
AIM
ALGORITHM
PROGRAM
importpygame
[Link] import *
[Link]()
screen = [Link].set_mode((400, 300))
done = False
while not done:
for event in [Link]():
[Link] == [Link]:
done = True
[Link](screen, (255,255,255), [100, 80], 10, 0)
[Link]()
[Link](screen, (0,0,0), [100, 80], 10, 0)
[Link]()
OUTPUT:
RESULT:
Thus, thepython program for bouncing ball in Pygame has been executed
successfully.
EX NO:12 B
DEVELOPING A GAME ACTIVITY USING PYGAME LIKE
DATE
CAR GAME
AIM
AIM
ALGORITHM
Step1: Start.
Step2: Install pip pygame, py-m pip install-U pygame-user",py-m pip install pygame.
Step3: Intializes all the imported pygame modules.
Step4: Takes a tuple or a list as its parameter to create a surface (tuple preferred)
Step5: By using update( ),quit( ),Surface fill( ) functions used to develop the gaming
applications with its parameters.
Step6: Time clock and event get functions used to perform the action on time.
Step7: Stop.
PROGRAM
WINDOWWIDTH = 800
WINDOWHEIGHT = 600
TEXTCOLOR = (255, 255, 255)
BACKGROUNDCOLOR = (0, 0, 0)
FPS = 40
BADDIEMINSIZE = 10
BADDIEMAXSIZE = 40
BADDIEMINSPEED = 8
BADDIEMAXSPEED = 8
ADDNEWBADDIERATE = 6
PLAYERMOVERATE = 5
count=3
def terminate():
[Link]()
[Link]()
defwaitForPlayerToPressKey():
while True:
for event in [Link]():
[Link] == QUIT:
terminate()
[Link] == KEYDOWN:
[Link] == K_ESCAPE: #escape quits
terminate()
return
defplayerHasHitBaddie(playerRect, baddies):
for b in baddies:
[Link](b['rect']):
return True
return False
defdrawText(text, font, surface, x, y):
textobj = [Link](text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
[Link] = (x, y)
[Link](textobj, textrect)
# set up pygame, the window, and the mouse cursor
[Link]()
mainClock = [Link]()
windowSurface = [Link].set_mode((WINDOWWIDTH, WINDOWHEIGHT))
[Link].set_caption('car race')
[Link].set_visible(False)
# fonts
font = [Link](None, 30)
# sounds
gameOverSound = [Link]('music/[Link]')
[Link]('music/[Link]')
laugh = [Link]('music/[Link]')
# images
playerImage = [Link]('image/[Link]')
car3 = [Link]('image/[Link]')
car4 = [Link]('image/[Link]')
playerRect = playerImage.get_rect()
baddieImage = [Link]('image/[Link]')
sample = [car3,car4,baddieImage]
wallLeft = [Link]('image/[Link]')
wallRight = [Link]('image/[Link]')
# "Start" screen
drawText('Press any key to start the game.', font, windowSurface, (WINDOWWIDTH / 3) - 30,
(WINDOWHEIGHT / 3))
drawText('And Enjoy', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT /
3)+30)
[Link]()
waitForPlayerToPressKey()
zero=0
if not [Link]("data/[Link]"):
f=open("data/[Link]",'w')
[Link](str(zero))
[Link]()
v=open("data/[Link]",'r')
topScore = int([Link]())
[Link]()
while (count>0):
# start of the game
baddies = []
score = 0
[Link] = (WINDOWWIDTH / 2, WINDOWHEIGHT - 50)
moveLeft = moveRight = moveUp = moveDown = False
reverseCheat = slowCheat = False
baddieAddCounter = 0
[Link](-1, 0.0)
while True: # the game loop
score += 1 # increase score
moveLeft = True
[Link] == K_RIGHT or [Link] == ord('d'):
moveLeft = False
moveRight = True
[Link] == K_UP or [Link] == ord('w'):
moveDown = False
moveUp = True
[Link] == K_DOWN or [Link] == ord('s'):
moveUp = False
moveDown = True
[Link] == KEYUP:
[Link] == ord('z'):
reverseCheat = False
score = 0
[Link] == ord('x'):
slowCheat = False
score = 0
[Link] == K_ESCAPE:
terminate()
[Link](sideLeft)
sideRight= {'rect': [Link](497,0,303,600),
'speed': [Link](BADDIEMINSPEED, BADDIEMAXSPEED),
'surface':[Link](wallRight, (303, 599)),
}
[Link](sideRight)
# Move the player around.
ifmoveLeft and [Link]> 0:
playerRect.move_ip(-1 * PLAYERMOVERATE, 0)
ifmoveRight and [Link]< WINDOWWIDTH:
playerRect.move_ip(PLAYERMOVERATE, 0)
ifmoveUp and [Link]> 0:
playerRect.move_ip(0, -1 * PLAYERMOVERATE)
ifmoveDown and [Link]< WINDOWHEIGHT:
playerRect.move_ip(0, PLAYERMOVERATE)
for b in baddies:
if not reverseCheat and not slowCheat:
b['rect'].move_ip(0, b['speed'])
elifreverseCheat:
b['rect'].move_ip(0, -5)
elifslowCheat:
b['rect'].move_ip(0, 1)
for b in baddies[:]:
if b['rect'].top > WINDOWHEIGHT:
[Link](b)
# Draw the game world on the window.
[Link](BACKGROUNDCOLOR)
# Draw the score and top score.
drawText('Score: %s' % (score), font, windowSurface, 128, 0)
drawText('Top Score: %s' % (topScore), font, windowSurface,128, 20)
drawText('Rest Life: %s' % (count), font, windowSurface,128, 40)
[Link](playerImage, playerRect)
for b in baddies:
[Link](b['surface'], b['rect'])
[Link]()
# Check if any of the car have hit the player.
ifplayerHasHitBaddie(playerRect, baddies):
if score >topScore:
g=open("data/[Link]",'w')
[Link](str(score))
[Link]()
topScore = score
break
[Link](FPS)
# "Game Over" screen.
[Link]()
count=count-1
[Link]()
[Link](1)
if (count==0):
[Link]()
drawText('Game over', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press any key to play again.', font, windowSurface, (WINDOWWIDTH / 3) - 80,
(WINDOWHEIGHT / 3) + 30)
[Link]()
[Link](2)
waitForPlayerToPressKey()
count=3
[Link]()
OUTPUT
RESULT
Thus, the program for Cargameusing pygame has been executed successfully.
MINI PROJECT
SOURCE CODE
OUTPUT
Tie!
Rock, Paper or Scissors?Paper
Tie!
Rock, Paper or Scissors?Scissors
You win! Scissors cut Paper
Rock, Paper or Scissors?