SlideShare a Scribd company logo
1 of 48
Download to read offline
GE3171 - PROBLEM SOLVING
AND
PYTHON PROGRAMMING
LABORATORY
(REG-2021)
LAB MANUEL
Compiled By:
Ramprakash.S
Teaching Faculty / CSE
University College of Engineering Thirukkuvalai
Nagapattinam -610204, Tamilnadu
1.Identification and solving of simple real life or scientific or technical problems, and
developing flow charts for the same.
a) Electricity Billing
Aim: Develop a flow chart and write the program for Electricity billing
Procedure:
From Unit To Unit Rate (Rs.) Prices
From Unit To Unit Rate (Rs.) Max.Unit
1 100 0 100
101 200 2 200
201 500 3 500-
- 101 -200 3.5 >500
201-500 4.6 >500
>500 606 >500
Flow Chart :
1b) Reatil Shop billing
Flow-Chart:
1c) Sin series
Flow Chart:
1d) To compute Electrical Current in Three Phase AC Circuit
Flow Chart :
Result :
2.a) Python programming using simple statements and expressions -exchange the values
of two variables)
Aim:
Write a python program to exchange the values of two variables
Procedure:
Code:
>>> a=10
>>> b=20
>>> a,b=b,a
>>>print(a)
>>>print(b)
output:
Result:
2b) Python programming using simple statements and expressions - circulate the values
of n variables)
Aim:
Write a python program to circulate the values of n variables
Procedure:
Code:
>>>list=[10,20,30,40,50]
>>>n=2
>>> print(list[n:]+list[:n])
output:
Result:
2 C) Python programming using simple statements and expressions ( Calculate the
distance between two points)
Aim:
Write a python program to calculate the distance between two numbers
Procedure:
Program:
import math
x1=int(input(“enter the value of x1”)
x2=int(input(“enter the value of x2”)
y1=int(input(“enter the value of y1”)
y2=int(input(“enter the value of y2”)
dx=x2-x1
dy=y2-y1
d= dx**2+d**2
result=math.sqrt(d)
print(result)
Output:
Result:
3 a) Scientific problems using Conditionals and Iterative loops.- Number series
Aim:
Write a Python program with conditional and iterative statements for
Number Series.
Procedure:
Program:
n=int(input("Enter a number: "))
a=[]
for i in range(1,n+1):
print(i,sep=" ",end=" ")
if(i<n):
print("+",sep=" ",end=" ")
a.append(i)
print("=",sum(a))
print()
output:
Result:
3 b) Scientific problems using Conditionals and Iterative loops. -Number Patterns
Aim:
Write a Python program with conditional and iterative statements for
Number Pattern.
Procedure:
Program:
rows = 6
rows = int(input('Enter the number of rows'))
for i in range(rows):
for j in range(i):
print(i, end=' ')
print('')
output:
Result:
3 c) Scientific problems using Conditionals and Iterative loops. -Pyramid Patterns
Aim:
Write a Python program with conditional and iterative statements for
Pyramid Pattern.
Procedure:
Program:
def pypart(n):
for i in range(0, n):
for j in range(0, i+1):
print("* ",end="")
print("r")
n = 5
pypart(n)
output:
Result:
4 a) Implementing real-time/technical applications using Lists, Tuples -Items present in a
library)
Aim :
Write a python program to implement items present in a library
Procedure:
Code:
library=["books", "author", "barcodenumber" , "price"]
library[0]="ramayanam"
print(library[0])
library[1]="valmiki"
library[2]=123987
library[3]=234
print(library)
Tuple:
tup1 = (12134,250000 )
tup2 = ('books', 'totalprice')
# tup1[0] = 100 ------- Not assigned in tuple
# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print(tup3)
Output:
Result
:
4 b) Implementing real-time/technical applications using Lists, Tuples -Components of a
car
Aim:
Write a python program to implement components of a car
Procedure:
Code:
cars = ["Nissan", "Mercedes Benz", "Ferrari", "Maserati", "Jeep", "Maruti Suzuki"]
new_list = []
for i in cars:
if "M" in i:
new_list.append(i)
print(new_list)
Tuple:
cars=("Ferrari", "BMW", "Audi", "Jaguar")
print(cars)
print(cars[0])
print(cars[1])
print(cars[3])
print(cars[3])
print(cars[4])
output:
Result:
4 C) Implementing real-time/technical applications using Lists, Tuples - Materials required
for construction of a building.
Aim:
Write a python program to implement materials required for construction of
building
Procedure:
Code:
materialsforconstruction = ["cementbags", "bricks", "sand", "Steelbars", "Paint"]
materialsforconstruction.append(“ Tiles”)
materialsforconstruction.insert(3,"Aggregates")
materialsforconstruction.remove("sand")
materialsforconstruction[5]="electrical"
print(materialsforconstruction)
Tuple:
materialsforconstruction = ("cementbags", "bricks", "sand", "Steelbars", "Paint")
print(materialsforconstruction)
del(materialsforconstruction)
print (After deleting materialsforconstruction)
print(materialsforconstruction)
print (“materialsforconstruction[0]:”, materialsforconstruction [0])
print (“materialsforconstruction [1:5]: ", materialsforconstruction [1:5])
output:
Result:
5a) Implementing real-time/technical applications using Sets, Dictionaries. - Language
Aim:
Write a python program to implement language system using Sets and Dictionaries
Procedure:
Code:
import re
ulysses_txt = open("books/james_joyce_ulysses.txt").read().lower()
words = re.findall(r"b[w-]+b", ulysses_txt)
print("The novel ulysses contains " + str(len(words)))
for word in ["the", "while", "good", "bad", "ireland", "irish"]:
print("The word '" + word + "' occurs " + 
str(words.count(word)) + " times in the novel!" )
diff_words = set(words)
print("'Ulysses' contains " + str(len(diff_words)) + " different words!")
output:
Result:
Ref: https://python-course.eu/python-tutorial/sets-examples.php
5b) Implementing real-time/technical applications using Sets, Dictionaries. – Components
of an automobile
Aim:
Write a python program to implement Components of an automobile using Sets and
Dictionaries
Procedure:
Code:
cars = {'BMW', 'Honda', 'Audi', 'Mercedes', 'Honda', 'Toyota', 'Ferrari', 'Tesla'}
print('Approach #1= ', cars)
print('==========')
print('Approach #2')
for car in cars:
print('Car name = {}'.format(car))
print('==========')
cars.add('Tata')
print('New cars set = {}'.format(cars))
cars.discard('Mercedes')
print('discard() method = {}'.format(cars))
output:
Result:
https://www.javacodegeeks.com/sets-in-python.html
6a. Implementing programs using Functions – Factorial
Aim:
Write a python program to implement Factorial program using functions
Procedure:
Code:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
n=int(input("Input a number to compute the factiorial : "))
print(factorial(n))
output:
Result:
6b. Implementing programs using Functions – largest number in a list
Aim:
Write a python program to implement largest number in a list using functions
Procedure:
Code:
def myMax(list1):
max = list1[0]
for x in list1:
if x > max :
max = x
return max
list1 = [10, 20, 4, 45, 99]
print("Largest element is:", myMax(list1))
Output:
Result:
6c. Implementing programs using Functions – area of shape
Aim:
Write a python program to implement area of shape using functions
Procedure:
Code:
def calculate_area(name):
name = name.lower()
if name == "rectangle":
l = int(input("Enter rectangle's length: "))
b = int(input("Enter rectangle's breadth: "))
rect_area = l * b
print(f"The area of rectangle is
{rect_area}.")
elif name == "square":
s = int(input("Enter square's side length: "))
sqt_area = s * s
print(f"The area of square is
{sqt_area}.")
elif name == "triangle":
h = int(input("Enter triangle's height length: "))
b = int(input("Enter triangle's breadth length: "))
tri_area = 0.5 * b * h
print(f"The area of triangle is
{tri_area}.")
elif name == "circle":
r = int(input("Enter circle's radius length: "))
pi = 3.14
circ_area = pi * r * r
print(f"The area of triangle is
{circ_area}.")
elif name == 'parallelogram':
b = int(input("Enter parallelogram's base length: "))
h = int(input("Enter parallelogram's height length: "))
# calculate area of parallelogram
para_area = b * h
print(f"The area of parallelogram is
{para_area}.")
else:
print("Sorry! This shape is not available")
if __name__ == "__main__" :
print("Calculate Shape Area")
shape_name = input("Enter the name of shape whose area you want to find: ")
calculate_area(shape_name)
Output:
Result:
7 a. Implementing programs using Strings –Reverse
Aim:
Write a python program to implement reverse of a string using string functions
Procedure:
Code:
def reverse(string):
string = string[::-1]
return string
s = "Firstyearece"
print ("The original string is : ",end="")
print (s)
print ("The reversed string(using extended slice syntax) is : ",end="")
print (reverse(s))
output:
Result:
7 b. Implementing programs using Strings -palindrome
Aim:
Write a python program to implement palindrome using string functions
Procedure:
Code:
string=input(("Enter a string:"))
if(string==string[::-1]):
print("The string is a palindrome")
else:
print("Not a palindrome")
output:
Result:
7 c. Implementing programs using Strings - character count
Aim:
Write a python program to implement Characters count using string functions
Procedure:
Code:
test_str = "Countthethesisthirdtime"
count = 0
for i in test_str:
if i == 't':
count = count + 1
print ("Count of e in Countthethesisthirdtim is : " + str(count))
output:
Result:
7.d) Implementing programs using Strings – Replacing Characters
Aim:
Write a python program to implement Replacing Characetrs using string functions
Procedure:
Code:
string = "geeks for geeks geeks geeks geeks"
print(string.replace("e", "a"))
print(string.replace("ek", "a", 3))
output:
Result:
8.a) Implementing programs using written modules and Python Standard Libraries –pandas
Aim:
Write a python program to implement pandas modules.Pandas are denote
python datastructures.
Procedure:
Code:
In command prompt install this package
pip install pandas
import pandas as pd
df = pd.DataFrame(
{
"Name": [ "Braund, Mr. Owen Harris",
"Allen, Mr. William Henry",
"Bonnell, Miss. Elizabeth",],
"Age": [22, 35, 58],
"Sex": ["male", "male", "female"],
}
)
print(df)
print(df[“Age”])
ages = pd.Series([22, 35, 58], name="Age")
print(ages)
df["Age"].max()
print(ages.max())
print(df.describe())
output:
Result:
8.b) Implementing programs using written modules and Python Standard Libraries – numpy
Aim:
Write a python program to implement numpy module in python .Numerical
python are mathematical calculations are solved here.
Procedure:
Code: In command prompt install this package
pip install numpy
import numpy as np
a = np.arange(6)
a2 = a[np.newaxis, :]
a2.shape
output:
Array Creation and functions:
a = np.array([1, 2, 3, 4, 5, 6])
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(a[0])
print(a[1])
np.zeros(2)
np.ones(2)
np.arange(4)
np.arange(2, 9, 2)
np.linspace(0, 10, num=5)
x = np.ones(2, dtype=np.int64)
print(x)
arr = np.array([2, 1, 5, 3, 7, 4, 6, 8])
np.sort(arr)
a = np.array([1, 2, 3, 4])
b = np.array([5, 6, 7, 8])
np.concatenate((a, b))
Array Dimensions:
array_example = np.array([[[0, 1, 2, 3],
... [4, 5, 6, 7]],
...
... [[0, 1, 2, 3],
... [4, 5, 6, 7]],
...
... [[0 ,1 ,2, 3],
... [4, 5, 6, 7]]])
array_example.ndim
array_example.size
array_example.shape
a = np.arange(6)
print(a)
b = a.reshape(3, 2)
print(b)
np.reshape(a, newshape=(1, 6), order='C')
outputs:
Result:
8.c) Implementing programs using written modules and Python Standard Libraries –matplotlib
Aim:
Write a python program to implement matplotolib module in python. .Matplotlib
python are used to show the visualization entites in python.
Procedure:
Code: In command prompt install this package
pip install matplotlib
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('_mpl-gallery')
x = np.linspace(0, 10, 100)
y = 4 + 2 * np.sin(2 * x)
fig, ax = plt.subplots()
ax.plot(x, y, linewidth=2.0)
ax.set(xlim=(0, 8), xticks=np.arange(1, 8),
ylim=(0, 8), yticks=np.arange(1, 8))
plt.show()
output:
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('_mpl-gallery')
np.random.seed(1)
x = 4 + np.random.normal(0, 1.5, 200)
fig, ax = plt.subplots()
ax.hist(x, bins=8, linewidth=0.5, edgecolor="white")
ax.set(xlim=(0, 8), xticks=np.arange(1, 8),
ylim=(0, 56), yticks=np.linspace(0, 56, 9))
plt.show()
output
Result:
8.d) Implementing programs using written modules and Python Standard Libraries – scipy
Aim:
Write a python program to implement scipy module in python. .Scipy python
are used to solve the scientific calculations.
Procedure:
Code: In command prompt install this package
pip install scipy
1-D discrete Fourier transforms¶
from scipy.fft import fft, ifft
x = np.array([1.0, 2.0, 1.0, -1.0, 1.5])
y = fft(x)
y
array([ 4.5 +0.j , 2.08155948-1.65109876j,
-1.83155948+1.60822041j, -1.83155948-1.60822041j,
2.08155948+1.65109876j])
yinv = ifft(y)
>>> yinv
Output:
from scipy.fft import fft, fftfreq
>>> # Number of sample points
>>> N = 600
>>> # sample spacing
>>> T = 1.0 / 800.0
>>> x = np.linspace(0.0, N*T, N, endpoint=False)
>>> y = np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x)
>>> yf = fft(y)
>>> xf = fftfreq(N, T)[:N//2]
>>> import matplotlib.pyplot as plt
>>> plt.plot(xf, 2.0/N * np.abs(yf[0:N//2]))
>>> plt.grid()
>>> plt.show()
Output:
Result:
9.a) Implementing real-time/technical applications using File handling - copy from one file
to another.
Aim:
Write a python program to implement File Copying
Procedure:
Code:
import shutil
original = r'original path where the file is currently storedfile name.file extension'
target = r'target path where the file will be copiedfile name.file extension'
shutil.copyfile(original, target)
Steps to follow:
Step 1: Capture the original path
To begin, capture the path where your file is currently stored.
For example, I stored a CSV file in a folder called Test_1:
C:UsersRonDesktopTest_1products.csv
Where the CSV file name is „products„ and the file extension is csv.
Step 2: Capture the target path
Next, capture the target path where you‟d like to copy the file.
In my case, the file will be copied into a folder called Test_2:
C:UsersRonDesktopTest_2products.csv
Step 3: Copy the file in Python using shutil.copyfile
import shutil
original = r'C:UsersRonDesktopTest_1products.csv'
target = r'C:UsersRonDesktopTest_2products.csv'
shutil.copyfile(original, target)
Ref :https://datatofish.com/copy-file-python/
Result:
9.b ) Implementing real-time/technical applications using File handling word count
Aim:
Write a python program to implement word count in File operations in python
Procedure:
Code:
Create file ece.txt with the following input
Welcome to python examples. Here, you will find python programs for all
general use cases.
file = open("C:ece.txt", "rt")
data = file.read()
words = data.split()
print('Number of words in text file :', len(words))
output:
Result:
9.c ) Implementing real-time/technical applications using File handling - Longest word
Aim:
Write a python program to implement longest word in File operations
Procedure:
Code:
Create a file test.txt and give the longest word
(e.x) hi I have pendrive
def longest_word(filename):
with open(filename, 'r') as infile:
words = infile.read().split()
max_len = len(max(words, key=len))
return [word for word in words if len(word) == max_len]
print(longest_word('test.txt'))
output:
Result:
10. a. Implementing real-time/technical applications using Exception handling.- divide by
zero error.
Aim:
Write a exception handling program using python to depict the divide by zero
error.
Procedure:
Code:
(i) marks = 10000
a = marks / 0
print(a)
(ii) program
a=int(input("Entre a="))
b=int(input("Entre b="))
try:
c = ((a+b) / (a-b))
#Raising Error
if a==b:
raise ZeroDivisionError
#Handling of error
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)
output:
Result:
10. C. Implementing real-time/technical applications using Exception handling.- Check
voters eligibility
Aim:
Write a exception handling program using python to depict the voters eligibility
Procedure:
Code:
try:
#this program check voting eligibility
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:
Result:
11. Exploring Pygame tool.
Aim:
Write a python program to implement pygame
Procedure:
Code:
To install Pygame in command prompt
Pip install pygame
import pygame
from pygame.locals import *
class Square(pygame.sprite.Sprite):
def __init__(self):
super(Square, self).__init__()
self.surf = pygame.Surface((25, 25))
self.surf.fill((0, 200, 255))
self.rect = self.surf.get_rect()
pygame.init()
screen = pygame.display.set_mode((800, 600))
square1 = Square()
square2 = Square()
square3 = Square()
square4 = Square()
gameOn = True
while gameOn:
for event in pygame.event.get():
PIP install pygame
if event.type == KEYDOWN:
if event.key == K_BACKSPACE:
gameOn = False
elif event.type == QUIT:
gameOn = False
screen.blit(square1.surf, (40, 40))
screen.blit(square2.surf, (40, 530))
screen.blit(square3.surf, (730, 40))
screen.blit(square4.surf, (730, 530))
pygame.display.flip()
Output:
Result:
12.a ) Developing a game activity using Pygame like bouncing ball.
Aim:
Write a python program to implement bouncing balls using pygame tool
Procedure:
Code:
import sys, pygame
pygame.init()
size = width, height = 800, 400
speed = [1, 1]
background = 255, 255, 255
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Bouncing ball")
ball = pygame.image.load("ball.png")
ballrect = ball.get_rect()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.fill(background)
screen.blit(ball, ballrect)
pygame.display.flip()
output:
Result:
12.b ) Developing a game activity using Pygame like Car race
Aim:
Write a python program to implement car race using pygame tool
Procedure:
Code:
import pygame, random, sys ,os,time
from pygame.locals import *
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():
pygame.quit()
sys.exit()
def waitForPlayerToPressKey():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE: #escape quits
terminate()
return
def playerHasHitBaddie(playerRect, baddies):
for b in baddies:
if playerRect.colliderect(b['rect']):
return True
return False
def drawText(text, font, surface, x, y):
textobj = font.render(text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
# set up pygame, the window, and the mouse cursor
pygame.init()
mainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('car race')
pygame.mouse.set_visible(False)
# fonts
font = pygame.font.SysFont(None, 30)
# sounds
gameOverSound = pygame.mixer.Sound('music/crash.wav')
pygame.mixer.music.load('music/car.wav')
laugh = pygame.mixer.Sound('music/laugh.wav')
# images
playerImage = pygame.image.load('image/car1.png')
car3 = pygame.image.load('image/car3.png')
car4 = pygame.image.load('image/car4.png')
playerRect = playerImage.get_rect()
baddieImage = pygame.image.load('image/car2.png')
sample = [car3,car4,baddieImage]
wallLeft = pygame.image.load('image/left.png')
wallRight = pygame.image.load('image/right.png')
# "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)
pygame.display.update()
waitForPlayerToPressKey()
zero=0
if not os.path.exists("data/save.dat"):
f=open("data/save.dat",'w')
f.write(str(zero))
f.close()
v=open("data/save.dat",'r')
topScore = int(v.readline())
v.close()
while (count>0):
# start of the game
baddies = []
score = 0
playerRect.topleft = (WINDOWWIDTH / 2, WINDOWHEIGHT - 50)
moveLeft = moveRight = moveUp = moveDown = False
reverseCheat = slowCheat = False
baddieAddCounter = 0
pygame.mixer.music.play(-1, 0.0)
while True: # the game loop
score += 1 # increase score
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == ord('z'):
reverseCheat = True
if event.key == ord('x'):
slowCheat = True
if event.key == K_LEFT or event.key == ord('a'):
moveRight = False
moveLeft = True
if event.key == K_RIGHT or event.key == ord('d'):
moveLeft = False
moveRight = True
if event.key == K_UP or event.key == ord('w'):
moveDown = False
moveUp = True
if event.key == K_DOWN or event.key == ord('s'):
moveUp = False
moveDown = True
if event.type == KEYUP:
if event.key == ord('z'):
reverseCheat = False
score = 0
if event.key == ord('x'):
slowCheat = False
score = 0
if event.key == K_ESCAPE:
terminate()
if event.key == K_LEFT or event.key == ord('a'):
moveLeft = False
if event.key == K_RIGHT or event.key == ord('d'):
moveRight = False
if event.key == K_UP or event.key == ord('w'):
moveUp = False
if event.key == K_DOWN or event.key == ord('s'):
moveDown = False
# Add new baddies at the top of the screen
if not reverseCheat and not slowCheat:
baddieAddCounter += 1
if baddieAddCounter == ADDNEWBADDIERATE:
baddieAddCounter = 0
baddieSize =30
newBaddie = {'rect': pygame.Rect(random.randint(140, 485), 0 - baddieSize, 23,
47),
'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED),
'surface':pygame.transform.scale(random.choice(sample), (23, 47)),
}
baddies.append(newBaddie)
sideLeft= {'rect': pygame.Rect(0,0,126,600),
'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED),
'surface':pygame.transform.scale(wallLeft, (126, 599)),
}
baddies.append(sideLeft)
sideRight= {'rect': pygame.Rect(497,0,303,600),
'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED),
'surface':pygame.transform.scale(wallRight, (303, 599)),
}
baddies.append(sideRight)
# Move the player around.
if moveLeft and playerRect.left > 0:
playerRect.move_ip(-1 * PLAYERMOVERATE, 0)
if moveRight and playerRect.right < WINDOWWIDTH:
playerRect.move_ip(PLAYERMOVERATE, 0)
if moveUp and playerRect.top > 0:
playerRect.move_ip(0, -1 * PLAYERMOVERATE)
if moveDown and playerRect.bottom < WINDOWHEIGHT:
playerRect.move_ip(0, PLAYERMOVERATE)
for b in baddies:
if not reverseCheat and not slowCheat:
b['rect'].move_ip(0, b['speed'])
elif reverseCheat:
b['rect'].move_ip(0, -5)
elif slowCheat:
b['rect'].move_ip(0, 1)
for b in baddies[:]:
if b['rect'].top > WINDOWHEIGHT:
baddies.remove(b)
# Draw the game world on the window.
windowSurface.fill(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)
windowSurface.blit(playerImage, playerRect)
for b in baddies:
windowSurface.blit(b['surface'], b['rect'])
pygame.display.update()
# Check if any of the car have hit the player.
if playerHasHitBaddie(playerRect, baddies):
if score > topScore:
g=open("data/save.dat",'w')
g.write(str(score))
g.close()
topScore = score
break
mainClock.tick(FPS)
# "Game Over" screen.
pygame.mixer.music.stop()
count=count-1
gameOverSound.play()
time.sleep(1)
if (count==0):
laugh.play()
drawText('Game over', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT
/ 3))
drawText('Press any key to play again.', font, windowSurface, (WINDOWWIDTH / 3) -
80, (WINDOWHEIGHT / 3) + 30)
pygame.display.update()
time.sleep(2)
waitForPlayerToPressKey()
count=3
gameOverSound.stop()
Output:
Result:
Refrences:
 www.geeksforgeeks.org/
 https://Pygame.com
 https://www.freecodecamp.org/news/exception-handling-python/
 https://www.rebootacademy.in/exception-handling/
 https://www.goeduhub.com/3552/python-program-to-bouncing-ball-in-pygame
 https://github.com
 www.matplotlib.com
 www.scipy.com
 www.pandas.com
 www.numpy.com

More Related Content

What's hot

How to download and install Python - lesson 2
How to download and install Python - lesson 2How to download and install Python - lesson 2
How to download and install Python - lesson 2Shohel Rana
 
Data types in python
Data types in pythonData types in python
Data types in pythonRaginiJain21
 
Python Programming ppt
Python Programming pptPython Programming ppt
Python Programming pptismailmrribi
 
Packages In Python Tutorial
Packages In Python TutorialPackages In Python Tutorial
Packages In Python TutorialSimplilearn
 
Transfer Learning: An overview
Transfer Learning: An overviewTransfer Learning: An overview
Transfer Learning: An overviewjins0618
 
Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Edureka!
 
Python programs - first semester computer lab manual (polytechnics)
Python programs - first semester computer lab manual (polytechnics)Python programs - first semester computer lab manual (polytechnics)
Python programs - first semester computer lab manual (polytechnics)SHAMJITH KM
 
Language processing activity
Language processing activityLanguage processing activity
Language processing activityDhruv Sabalpara
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in pythonTMARAGATHAM
 
Python Summer Internship
Python Summer InternshipPython Summer Internship
Python Summer InternshipAtul Kumar
 
Network lab manual
Network lab manualNetwork lab manual
Network lab manualPrabhu D
 

What's hot (20)

How to download and install Python - lesson 2
How to download and install Python - lesson 2How to download and install Python - lesson 2
How to download and install Python - lesson 2
 
Python ppt
Python pptPython ppt
Python ppt
 
Python numbers
Python numbersPython numbers
Python numbers
 
Data types in python
Data types in pythonData types in python
Data types in python
 
Python Programming ppt
Python Programming pptPython Programming ppt
Python Programming ppt
 
Packages In Python Tutorial
Packages In Python TutorialPackages In Python Tutorial
Packages In Python Tutorial
 
Transfer Learning: An overview
Transfer Learning: An overviewTransfer Learning: An overview
Transfer Learning: An overview
 
Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...
 
Python : Regular expressions
Python : Regular expressionsPython : Regular expressions
Python : Regular expressions
 
Python programs - first semester computer lab manual (polytechnics)
Python programs - first semester computer lab manual (polytechnics)Python programs - first semester computer lab manual (polytechnics)
Python programs - first semester computer lab manual (polytechnics)
 
Storage class in C Language
Storage class in C LanguageStorage class in C Language
Storage class in C Language
 
Language processing activity
Language processing activityLanguage processing activity
Language processing activity
 
Python basics
Python basicsPython basics
Python basics
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
 
Python Summer Internship
Python Summer InternshipPython Summer Internship
Python Summer Internship
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
 
Introduction to python
 Introduction to python Introduction to python
Introduction to python
 
Type conversion
Type conversionType conversion
Type conversion
 
Network lab manual
Network lab manualNetwork lab manual
Network lab manual
 
Templates
TemplatesTemplates
Templates
 

Similar to GE3171 - PROBLEM SOLVING AND PYTHON PROGRAMMING LAB MANUAL

c++ exp 1 Suraj...pdf
c++ exp 1 Suraj...pdfc++ exp 1 Suraj...pdf
c++ exp 1 Suraj...pdfayush616992
 
Advanced Web Technology ass.pdf
Advanced Web Technology ass.pdfAdvanced Web Technology ass.pdf
Advanced Web Technology ass.pdfsimenehanmut
 
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docxJLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docxvrickens
 
Question 1 briefly respond to all the following questions. make
Question 1 briefly respond to all the following questions. make Question 1 briefly respond to all the following questions. make
Question 1 briefly respond to all the following questions. make YASHU40
 
Python 03-parameters-graphics.pptx
Python 03-parameters-graphics.pptxPython 03-parameters-graphics.pptx
Python 03-parameters-graphics.pptxTseChris
 
Java Question-Bank-Class-8.pdf
Java Question-Bank-Class-8.pdfJava Question-Bank-Class-8.pdf
Java Question-Bank-Class-8.pdfAditya Kumar
 
C and Data structure lab manual ECE (2).pdf
C and Data structure lab manual ECE (2).pdfC and Data structure lab manual ECE (2).pdf
C and Data structure lab manual ECE (2).pdfjanakim15
 
C programming Lab 1
C programming Lab 1C programming Lab 1
C programming Lab 1Zaibi Gondal
 
Char word counter in Python with simple gui - PROJECT
Char word counter in Python with simple gui - PROJECTChar word counter in Python with simple gui - PROJECT
Char word counter in Python with simple gui - PROJECTMahmutKAMALAK
 
Pemrograman Python untuk Pemula
Pemrograman Python untuk PemulaPemrograman Python untuk Pemula
Pemrograman Python untuk PemulaOon Arfiandwi
 
project report in C++ programming and SQL
project report in C++ programming and SQLproject report in C++ programming and SQL
project report in C++ programming and SQLvikram mahendra
 
function in in thi pdf you will learn what is fu...
function in  in thi pdf you will learn   what                           is fu...function in  in thi pdf you will learn   what                           is fu...
function in in thi pdf you will learn what is fu...kushwahashivam413
 

Similar to GE3171 - PROBLEM SOLVING AND PYTHON PROGRAMMING LAB MANUAL (20)

Ankita sharma focp
Ankita sharma focpAnkita sharma focp
Ankita sharma focp
 
c++ exp 1 Suraj...pdf
c++ exp 1 Suraj...pdfc++ exp 1 Suraj...pdf
c++ exp 1 Suraj...pdf
 
Advanced Web Technology ass.pdf
Advanced Web Technology ass.pdfAdvanced Web Technology ass.pdf
Advanced Web Technology ass.pdf
 
C++ manual Report Full
C++ manual Report FullC++ manual Report Full
C++ manual Report Full
 
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docxJLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
 
Question 1 briefly respond to all the following questions. make
Question 1 briefly respond to all the following questions. make Question 1 briefly respond to all the following questions. make
Question 1 briefly respond to all the following questions. make
 
Python 03-parameters-graphics.pptx
Python 03-parameters-graphics.pptxPython 03-parameters-graphics.pptx
Python 03-parameters-graphics.pptx
 
Objects and Graphics
Objects and GraphicsObjects and Graphics
Objects and Graphics
 
Java Question-Bank-Class-8.pdf
Java Question-Bank-Class-8.pdfJava Question-Bank-Class-8.pdf
Java Question-Bank-Class-8.pdf
 
C++
C++C++
C++
 
LMmanual.pdf
LMmanual.pdfLMmanual.pdf
LMmanual.pdf
 
Muzzammilrashid
MuzzammilrashidMuzzammilrashid
Muzzammilrashid
 
Chapter04.pptx
Chapter04.pptxChapter04.pptx
Chapter04.pptx
 
Unit-IV.pptx
Unit-IV.pptxUnit-IV.pptx
Unit-IV.pptx
 
C and Data structure lab manual ECE (2).pdf
C and Data structure lab manual ECE (2).pdfC and Data structure lab manual ECE (2).pdf
C and Data structure lab manual ECE (2).pdf
 
C programming Lab 1
C programming Lab 1C programming Lab 1
C programming Lab 1
 
Char word counter in Python with simple gui - PROJECT
Char word counter in Python with simple gui - PROJECTChar word counter in Python with simple gui - PROJECT
Char word counter in Python with simple gui - PROJECT
 
Pemrograman Python untuk Pemula
Pemrograman Python untuk PemulaPemrograman Python untuk Pemula
Pemrograman Python untuk Pemula
 
project report in C++ programming and SQL
project report in C++ programming and SQLproject report in C++ programming and SQL
project report in C++ programming and SQL
 
function in in thi pdf you will learn what is fu...
function in  in thi pdf you will learn   what                           is fu...function in  in thi pdf you will learn   what                           is fu...
function in in thi pdf you will learn what is fu...
 

More from RamprakashSingaravel1

More from RamprakashSingaravel1 (7)

OVS.pptx
OVS.pptxOVS.pptx
OVS.pptx
 
WSN_Chapter 4 Routing Protocols-I.pptx
WSN_Chapter 4 Routing Protocols-I.pptxWSN_Chapter 4 Routing Protocols-I.pptx
WSN_Chapter 4 Routing Protocols-I.pptx
 
Data Visualization
Data VisualizationData Visualization
Data Visualization
 
Orange Software
Orange Software Orange Software
Orange Software
 
Introduction to Data Science, Applications & Opportunities.pdf
Introduction to Data Science, Applications & Opportunities.pdfIntroduction to Data Science, Applications & Opportunities.pdf
Introduction to Data Science, Applications & Opportunities.pdf
 
Data Visualization
Data VisualizationData Visualization
Data Visualization
 
nservice teacher training prgram.pdf
nservice teacher training prgram.pdfnservice teacher training prgram.pdf
nservice teacher training prgram.pdf
 

Recently uploaded

Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfKamal Acharya
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Christo Ananth
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsRussian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...Call Girls in Nagpur High Profile
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 

Recently uploaded (20)

Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdfONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
ONLINE FOOD ORDER SYSTEM PROJECT REPORT.pdf
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur EscortsRussian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
Russian Call Girls in Nagpur Grishma Call 7001035870 Meet With Nagpur Escorts
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 

GE3171 - PROBLEM SOLVING AND PYTHON PROGRAMMING LAB MANUAL

  • 1. GE3171 - PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY (REG-2021) LAB MANUEL Compiled By: Ramprakash.S Teaching Faculty / CSE University College of Engineering Thirukkuvalai Nagapattinam -610204, Tamilnadu
  • 2. 1.Identification and solving of simple real life or scientific or technical problems, and developing flow charts for the same. a) Electricity Billing Aim: Develop a flow chart and write the program for Electricity billing Procedure: From Unit To Unit Rate (Rs.) Prices From Unit To Unit Rate (Rs.) Max.Unit 1 100 0 100 101 200 2 200 201 500 3 500- - 101 -200 3.5 >500 201-500 4.6 >500 >500 606 >500 Flow Chart :
  • 3. 1b) Reatil Shop billing Flow-Chart:
  • 5. 1d) To compute Electrical Current in Three Phase AC Circuit Flow Chart : Result :
  • 6. 2.a) Python programming using simple statements and expressions -exchange the values of two variables) Aim: Write a python program to exchange the values of two variables Procedure: Code: >>> a=10 >>> b=20 >>> a,b=b,a >>>print(a) >>>print(b) output: Result:
  • 7. 2b) Python programming using simple statements and expressions - circulate the values of n variables) Aim: Write a python program to circulate the values of n variables Procedure: Code: >>>list=[10,20,30,40,50] >>>n=2 >>> print(list[n:]+list[:n]) output: Result:
  • 8. 2 C) Python programming using simple statements and expressions ( Calculate the distance between two points) Aim: Write a python program to calculate the distance between two numbers Procedure: Program: import math x1=int(input(“enter the value of x1”) x2=int(input(“enter the value of x2”) y1=int(input(“enter the value of y1”) y2=int(input(“enter the value of y2”) dx=x2-x1 dy=y2-y1 d= dx**2+d**2 result=math.sqrt(d) print(result) Output: Result:
  • 9. 3 a) Scientific problems using Conditionals and Iterative loops.- Number series Aim: Write a Python program with conditional and iterative statements for Number Series. Procedure: Program: n=int(input("Enter a number: ")) a=[] for i in range(1,n+1): print(i,sep=" ",end=" ") if(i<n): print("+",sep=" ",end=" ") a.append(i) print("=",sum(a)) print() output: Result:
  • 10. 3 b) Scientific problems using Conditionals and Iterative loops. -Number Patterns Aim: Write a Python program with conditional and iterative statements for Number Pattern. Procedure: Program: rows = 6 rows = int(input('Enter the number of rows')) for i in range(rows): for j in range(i): print(i, end=' ') print('') output: Result:
  • 11. 3 c) Scientific problems using Conditionals and Iterative loops. -Pyramid Patterns Aim: Write a Python program with conditional and iterative statements for Pyramid Pattern. Procedure: Program: def pypart(n): for i in range(0, n): for j in range(0, i+1): print("* ",end="") print("r") n = 5 pypart(n) output: Result:
  • 12. 4 a) Implementing real-time/technical applications using Lists, Tuples -Items present in a library) Aim : Write a python program to implement items present in a library Procedure: Code: library=["books", "author", "barcodenumber" , "price"] library[0]="ramayanam" print(library[0]) library[1]="valmiki" library[2]=123987 library[3]=234 print(library) Tuple: tup1 = (12134,250000 ) tup2 = ('books', 'totalprice') # tup1[0] = 100 ------- Not assigned in tuple # So let's create a new tuple as follows tup3 = tup1 + tup2; print(tup3) Output: Result :
  • 13. 4 b) Implementing real-time/technical applications using Lists, Tuples -Components of a car Aim: Write a python program to implement components of a car Procedure: Code: cars = ["Nissan", "Mercedes Benz", "Ferrari", "Maserati", "Jeep", "Maruti Suzuki"] new_list = [] for i in cars: if "M" in i: new_list.append(i) print(new_list) Tuple: cars=("Ferrari", "BMW", "Audi", "Jaguar") print(cars) print(cars[0]) print(cars[1]) print(cars[3]) print(cars[3]) print(cars[4]) output: Result:
  • 14. 4 C) Implementing real-time/technical applications using Lists, Tuples - Materials required for construction of a building. Aim: Write a python program to implement materials required for construction of building Procedure: Code: materialsforconstruction = ["cementbags", "bricks", "sand", "Steelbars", "Paint"] materialsforconstruction.append(“ Tiles”) materialsforconstruction.insert(3,"Aggregates") materialsforconstruction.remove("sand") materialsforconstruction[5]="electrical" print(materialsforconstruction) Tuple: materialsforconstruction = ("cementbags", "bricks", "sand", "Steelbars", "Paint") print(materialsforconstruction) del(materialsforconstruction) print (After deleting materialsforconstruction) print(materialsforconstruction) print (“materialsforconstruction[0]:”, materialsforconstruction [0]) print (“materialsforconstruction [1:5]: ", materialsforconstruction [1:5]) output: Result:
  • 15. 5a) Implementing real-time/technical applications using Sets, Dictionaries. - Language Aim: Write a python program to implement language system using Sets and Dictionaries Procedure: Code: import re ulysses_txt = open("books/james_joyce_ulysses.txt").read().lower() words = re.findall(r"b[w-]+b", ulysses_txt) print("The novel ulysses contains " + str(len(words))) for word in ["the", "while", "good", "bad", "ireland", "irish"]: print("The word '" + word + "' occurs " + str(words.count(word)) + " times in the novel!" ) diff_words = set(words) print("'Ulysses' contains " + str(len(diff_words)) + " different words!") output: Result: Ref: https://python-course.eu/python-tutorial/sets-examples.php
  • 16. 5b) Implementing real-time/technical applications using Sets, Dictionaries. – Components of an automobile Aim: Write a python program to implement Components of an automobile using Sets and Dictionaries Procedure: Code: cars = {'BMW', 'Honda', 'Audi', 'Mercedes', 'Honda', 'Toyota', 'Ferrari', 'Tesla'} print('Approach #1= ', cars) print('==========') print('Approach #2') for car in cars: print('Car name = {}'.format(car)) print('==========') cars.add('Tata') print('New cars set = {}'.format(cars)) cars.discard('Mercedes') print('discard() method = {}'.format(cars)) output: Result: https://www.javacodegeeks.com/sets-in-python.html
  • 17. 6a. Implementing programs using Functions – Factorial Aim: Write a python program to implement Factorial program using functions Procedure: Code: def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) n=int(input("Input a number to compute the factiorial : ")) print(factorial(n)) output: Result:
  • 18. 6b. Implementing programs using Functions – largest number in a list Aim: Write a python program to implement largest number in a list using functions Procedure: Code: def myMax(list1): max = list1[0] for x in list1: if x > max : max = x return max list1 = [10, 20, 4, 45, 99] print("Largest element is:", myMax(list1)) Output: Result:
  • 19. 6c. Implementing programs using Functions – area of shape Aim: Write a python program to implement area of shape using functions Procedure: Code: def calculate_area(name): name = name.lower() if name == "rectangle": l = int(input("Enter rectangle's length: ")) b = int(input("Enter rectangle's breadth: ")) rect_area = l * b print(f"The area of rectangle is {rect_area}.") elif name == "square": s = int(input("Enter square's side length: ")) sqt_area = s * s print(f"The area of square is {sqt_area}.") elif name == "triangle": h = int(input("Enter triangle's height length: ")) b = int(input("Enter triangle's breadth length: ")) tri_area = 0.5 * b * h print(f"The area of triangle is {tri_area}.") elif name == "circle": r = int(input("Enter circle's radius length: ")) pi = 3.14 circ_area = pi * r * r print(f"The area of triangle is {circ_area}.") elif name == 'parallelogram': b = int(input("Enter parallelogram's base length: ")) h = int(input("Enter parallelogram's height length: "))
  • 20. # calculate area of parallelogram para_area = b * h print(f"The area of parallelogram is {para_area}.") else: print("Sorry! This shape is not available") if __name__ == "__main__" : print("Calculate Shape Area") shape_name = input("Enter the name of shape whose area you want to find: ") calculate_area(shape_name) Output: Result:
  • 21. 7 a. Implementing programs using Strings –Reverse Aim: Write a python program to implement reverse of a string using string functions Procedure: Code: def reverse(string): string = string[::-1] return string s = "Firstyearece" print ("The original string is : ",end="") print (s) print ("The reversed string(using extended slice syntax) is : ",end="") print (reverse(s)) output: Result:
  • 22. 7 b. Implementing programs using Strings -palindrome Aim: Write a python program to implement palindrome using string functions Procedure: Code: string=input(("Enter a string:")) if(string==string[::-1]): print("The string is a palindrome") else: print("Not a palindrome") output: Result:
  • 23. 7 c. Implementing programs using Strings - character count Aim: Write a python program to implement Characters count using string functions Procedure: Code: test_str = "Countthethesisthirdtime" count = 0 for i in test_str: if i == 't': count = count + 1 print ("Count of e in Countthethesisthirdtim is : " + str(count)) output: Result:
  • 24. 7.d) Implementing programs using Strings – Replacing Characters Aim: Write a python program to implement Replacing Characetrs using string functions Procedure: Code: string = "geeks for geeks geeks geeks geeks" print(string.replace("e", "a")) print(string.replace("ek", "a", 3)) output: Result:
  • 25. 8.a) Implementing programs using written modules and Python Standard Libraries –pandas Aim: Write a python program to implement pandas modules.Pandas are denote python datastructures. Procedure: Code: In command prompt install this package pip install pandas import pandas as pd df = pd.DataFrame( { "Name": [ "Braund, Mr. Owen Harris", "Allen, Mr. William Henry", "Bonnell, Miss. Elizabeth",], "Age": [22, 35, 58], "Sex": ["male", "male", "female"], } ) print(df) print(df[“Age”]) ages = pd.Series([22, 35, 58], name="Age") print(ages) df["Age"].max() print(ages.max()) print(df.describe()) output: Result:
  • 26. 8.b) Implementing programs using written modules and Python Standard Libraries – numpy Aim: Write a python program to implement numpy module in python .Numerical python are mathematical calculations are solved here. Procedure: Code: In command prompt install this package pip install numpy import numpy as np a = np.arange(6) a2 = a[np.newaxis, :] a2.shape output: Array Creation and functions: a = np.array([1, 2, 3, 4, 5, 6]) a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) print(a[0]) print(a[1]) np.zeros(2) np.ones(2) np.arange(4) np.arange(2, 9, 2) np.linspace(0, 10, num=5) x = np.ones(2, dtype=np.int64) print(x) arr = np.array([2, 1, 5, 3, 7, 4, 6, 8]) np.sort(arr)
  • 27. a = np.array([1, 2, 3, 4]) b = np.array([5, 6, 7, 8]) np.concatenate((a, b)) Array Dimensions: array_example = np.array([[[0, 1, 2, 3], ... [4, 5, 6, 7]], ... ... [[0, 1, 2, 3], ... [4, 5, 6, 7]], ... ... [[0 ,1 ,2, 3], ... [4, 5, 6, 7]]]) array_example.ndim array_example.size array_example.shape a = np.arange(6) print(a) b = a.reshape(3, 2) print(b) np.reshape(a, newshape=(1, 6), order='C') outputs: Result:
  • 28. 8.c) Implementing programs using written modules and Python Standard Libraries –matplotlib Aim: Write a python program to implement matplotolib module in python. .Matplotlib python are used to show the visualization entites in python. Procedure: Code: In command prompt install this package pip install matplotlib import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery') x = np.linspace(0, 10, 100) y = 4 + 2 * np.sin(2 * x) fig, ax = plt.subplots() ax.plot(x, y, linewidth=2.0) ax.set(xlim=(0, 8), xticks=np.arange(1, 8), ylim=(0, 8), yticks=np.arange(1, 8)) plt.show() output:
  • 29. import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery') np.random.seed(1) x = 4 + np.random.normal(0, 1.5, 200) fig, ax = plt.subplots() ax.hist(x, bins=8, linewidth=0.5, edgecolor="white") ax.set(xlim=(0, 8), xticks=np.arange(1, 8), ylim=(0, 56), yticks=np.linspace(0, 56, 9)) plt.show() output Result:
  • 30. 8.d) Implementing programs using written modules and Python Standard Libraries – scipy Aim: Write a python program to implement scipy module in python. .Scipy python are used to solve the scientific calculations. Procedure: Code: In command prompt install this package pip install scipy 1-D discrete Fourier transforms¶ from scipy.fft import fft, ifft x = np.array([1.0, 2.0, 1.0, -1.0, 1.5]) y = fft(x) y array([ 4.5 +0.j , 2.08155948-1.65109876j, -1.83155948+1.60822041j, -1.83155948-1.60822041j, 2.08155948+1.65109876j]) yinv = ifft(y) >>> yinv Output:
  • 31. from scipy.fft import fft, fftfreq >>> # Number of sample points >>> N = 600 >>> # sample spacing >>> T = 1.0 / 800.0 >>> x = np.linspace(0.0, N*T, N, endpoint=False) >>> y = np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x) >>> yf = fft(y) >>> xf = fftfreq(N, T)[:N//2] >>> import matplotlib.pyplot as plt >>> plt.plot(xf, 2.0/N * np.abs(yf[0:N//2])) >>> plt.grid() >>> plt.show() Output: Result:
  • 32. 9.a) Implementing real-time/technical applications using File handling - copy from one file to another. Aim: Write a python program to implement File Copying Procedure: Code: import shutil original = r'original path where the file is currently storedfile name.file extension' target = r'target path where the file will be copiedfile name.file extension' shutil.copyfile(original, target) Steps to follow: Step 1: Capture the original path To begin, capture the path where your file is currently stored. For example, I stored a CSV file in a folder called Test_1: C:UsersRonDesktopTest_1products.csv Where the CSV file name is „products„ and the file extension is csv.
  • 33. Step 2: Capture the target path Next, capture the target path where you‟d like to copy the file. In my case, the file will be copied into a folder called Test_2: C:UsersRonDesktopTest_2products.csv Step 3: Copy the file in Python using shutil.copyfile import shutil original = r'C:UsersRonDesktopTest_1products.csv' target = r'C:UsersRonDesktopTest_2products.csv' shutil.copyfile(original, target)
  • 35. 9.b ) Implementing real-time/technical applications using File handling word count Aim: Write a python program to implement word count in File operations in python Procedure: Code: Create file ece.txt with the following input Welcome to python examples. Here, you will find python programs for all general use cases. file = open("C:ece.txt", "rt") data = file.read() words = data.split() print('Number of words in text file :', len(words)) output: Result:
  • 36. 9.c ) Implementing real-time/technical applications using File handling - Longest word Aim: Write a python program to implement longest word in File operations Procedure: Code: Create a file test.txt and give the longest word (e.x) hi I have pendrive def longest_word(filename): with open(filename, 'r') as infile: words = infile.read().split() max_len = len(max(words, key=len)) return [word for word in words if len(word) == max_len] print(longest_word('test.txt')) output: Result:
  • 37. 10. a. Implementing real-time/technical applications using Exception handling.- divide by zero error. Aim: Write a exception handling program using python to depict the divide by zero error. Procedure: Code: (i) marks = 10000 a = marks / 0 print(a) (ii) program a=int(input("Entre a=")) b=int(input("Entre b=")) try: c = ((a+b) / (a-b)) #Raising Error if a==b: raise ZeroDivisionError #Handling of error except ZeroDivisionError: print ("a/b result in 0") else: print (c) output: Result:
  • 38. 10. C. Implementing real-time/technical applications using Exception handling.- Check voters eligibility Aim: Write a exception handling program using python to depict the voters eligibility Procedure: Code: try: #this program check voting eligibility 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: Result:
  • 39. 11. Exploring Pygame tool. Aim: Write a python program to implement pygame Procedure: Code: To install Pygame in command prompt Pip install pygame import pygame from pygame.locals import * class Square(pygame.sprite.Sprite): def __init__(self): super(Square, self).__init__() self.surf = pygame.Surface((25, 25)) self.surf.fill((0, 200, 255)) self.rect = self.surf.get_rect() pygame.init() screen = pygame.display.set_mode((800, 600)) square1 = Square() square2 = Square() square3 = Square() square4 = Square() gameOn = True while gameOn: for event in pygame.event.get(): PIP install pygame
  • 40. if event.type == KEYDOWN: if event.key == K_BACKSPACE: gameOn = False elif event.type == QUIT: gameOn = False screen.blit(square1.surf, (40, 40)) screen.blit(square2.surf, (40, 530)) screen.blit(square3.surf, (730, 40)) screen.blit(square4.surf, (730, 530)) pygame.display.flip() Output: Result:
  • 41. 12.a ) Developing a game activity using Pygame like bouncing ball. Aim: Write a python program to implement bouncing balls using pygame tool Procedure: Code: import sys, pygame pygame.init() size = width, height = 800, 400 speed = [1, 1] background = 255, 255, 255 screen = pygame.display.set_mode(size) pygame.display.set_caption("Bouncing ball") ball = pygame.image.load("ball.png") ballrect = ball.get_rect() while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() ballrect = ballrect.move(speed) if ballrect.left < 0 or ballrect.right > width: speed[0] = -speed[0]
  • 42. if ballrect.top < 0 or ballrect.bottom > height: speed[1] = -speed[1] screen.fill(background) screen.blit(ball, ballrect) pygame.display.flip() output: Result:
  • 43. 12.b ) Developing a game activity using Pygame like Car race Aim: Write a python program to implement car race using pygame tool Procedure: Code: import pygame, random, sys ,os,time from pygame.locals import * 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(): pygame.quit() sys.exit() def waitForPlayerToPressKey(): while True: for event in pygame.event.get(): if event.type == QUIT: terminate() if event.type == KEYDOWN: if event.key == K_ESCAPE: #escape quits terminate() return
  • 44. def playerHasHitBaddie(playerRect, baddies): for b in baddies: if playerRect.colliderect(b['rect']): return True return False def drawText(text, font, surface, x, y): textobj = font.render(text, 1, TEXTCOLOR) textrect = textobj.get_rect() textrect.topleft = (x, y) surface.blit(textobj, textrect) # set up pygame, the window, and the mouse cursor pygame.init() mainClock = pygame.time.Clock() windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) pygame.display.set_caption('car race') pygame.mouse.set_visible(False) # fonts font = pygame.font.SysFont(None, 30) # sounds gameOverSound = pygame.mixer.Sound('music/crash.wav') pygame.mixer.music.load('music/car.wav') laugh = pygame.mixer.Sound('music/laugh.wav') # images playerImage = pygame.image.load('image/car1.png') car3 = pygame.image.load('image/car3.png') car4 = pygame.image.load('image/car4.png') playerRect = playerImage.get_rect() baddieImage = pygame.image.load('image/car2.png') sample = [car3,car4,baddieImage] wallLeft = pygame.image.load('image/left.png') wallRight = pygame.image.load('image/right.png') # "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) pygame.display.update() waitForPlayerToPressKey() zero=0 if not os.path.exists("data/save.dat"): f=open("data/save.dat",'w') f.write(str(zero)) f.close() v=open("data/save.dat",'r')
  • 45. topScore = int(v.readline()) v.close() while (count>0): # start of the game baddies = [] score = 0 playerRect.topleft = (WINDOWWIDTH / 2, WINDOWHEIGHT - 50) moveLeft = moveRight = moveUp = moveDown = False reverseCheat = slowCheat = False baddieAddCounter = 0 pygame.mixer.music.play(-1, 0.0) while True: # the game loop score += 1 # increase score for event in pygame.event.get(): if event.type == QUIT: terminate() if event.type == KEYDOWN: if event.key == ord('z'): reverseCheat = True if event.key == ord('x'): slowCheat = True if event.key == K_LEFT or event.key == ord('a'): moveRight = False moveLeft = True if event.key == K_RIGHT or event.key == ord('d'): moveLeft = False moveRight = True if event.key == K_UP or event.key == ord('w'): moveDown = False moveUp = True if event.key == K_DOWN or event.key == ord('s'): moveUp = False moveDown = True if event.type == KEYUP: if event.key == ord('z'): reverseCheat = False score = 0 if event.key == ord('x'): slowCheat = False score = 0 if event.key == K_ESCAPE: terminate() if event.key == K_LEFT or event.key == ord('a'): moveLeft = False if event.key == K_RIGHT or event.key == ord('d'):
  • 46. moveRight = False if event.key == K_UP or event.key == ord('w'): moveUp = False if event.key == K_DOWN or event.key == ord('s'): moveDown = False # Add new baddies at the top of the screen if not reverseCheat and not slowCheat: baddieAddCounter += 1 if baddieAddCounter == ADDNEWBADDIERATE: baddieAddCounter = 0 baddieSize =30 newBaddie = {'rect': pygame.Rect(random.randint(140, 485), 0 - baddieSize, 23, 47), 'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED), 'surface':pygame.transform.scale(random.choice(sample), (23, 47)), } baddies.append(newBaddie) sideLeft= {'rect': pygame.Rect(0,0,126,600), 'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED), 'surface':pygame.transform.scale(wallLeft, (126, 599)), } baddies.append(sideLeft) sideRight= {'rect': pygame.Rect(497,0,303,600), 'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED), 'surface':pygame.transform.scale(wallRight, (303, 599)), } baddies.append(sideRight) # Move the player around. if moveLeft and playerRect.left > 0: playerRect.move_ip(-1 * PLAYERMOVERATE, 0) if moveRight and playerRect.right < WINDOWWIDTH: playerRect.move_ip(PLAYERMOVERATE, 0) if moveUp and playerRect.top > 0: playerRect.move_ip(0, -1 * PLAYERMOVERATE) if moveDown and playerRect.bottom < WINDOWHEIGHT: playerRect.move_ip(0, PLAYERMOVERATE) for b in baddies: if not reverseCheat and not slowCheat: b['rect'].move_ip(0, b['speed']) elif reverseCheat: b['rect'].move_ip(0, -5) elif slowCheat: b['rect'].move_ip(0, 1)
  • 47. for b in baddies[:]: if b['rect'].top > WINDOWHEIGHT: baddies.remove(b) # Draw the game world on the window. windowSurface.fill(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) windowSurface.blit(playerImage, playerRect) for b in baddies: windowSurface.blit(b['surface'], b['rect']) pygame.display.update() # Check if any of the car have hit the player. if playerHasHitBaddie(playerRect, baddies): if score > topScore: g=open("data/save.dat",'w') g.write(str(score)) g.close() topScore = score break mainClock.tick(FPS) # "Game Over" screen. pygame.mixer.music.stop() count=count-1 gameOverSound.play() time.sleep(1) if (count==0): laugh.play() drawText('Game over', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3)) drawText('Press any key to play again.', font, windowSurface, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 30) pygame.display.update() time.sleep(2) waitForPlayerToPressKey() count=3 gameOverSound.stop() Output: Result:
  • 48. Refrences:  www.geeksforgeeks.org/  https://Pygame.com  https://www.freecodecamp.org/news/exception-handling-python/  https://www.rebootacademy.in/exception-handling/  https://www.goeduhub.com/3552/python-program-to-bouncing-ball-in-pygame  https://github.com  www.matplotlib.com  www.scipy.com  www.pandas.com  www.numpy.com