0% found this document useful (0 votes)
3 views48 pages

2302cs303-Problem Solving Using Python-Lab Manual

Uploaded by

ad20250001
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views48 pages

2302cs303-Problem Solving Using Python-Lab Manual

Uploaded by

ad20250001
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

E.G.

S PILLAY ENGINEERING COLLEGE (AUTONOMOUS)


NAGAPATTINAM – 611 002.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

2302CS303-PROBLEM SOLVING USING PYTHON

LAB MANUAL

REGULATION 2023

Year / Semester: II / III


INDEX

[Link] [Link] List of Programs Page. No Date Sign


Python programming using simple
statements and expressions
1 1A Exchange the values of two variables
1B Circulate the values of n variables
1C Distance between two points
Scientific problems using Conditionals and
Iterative loops.
2 2A Number series
2B Number Patterns
2C Pyramid pattern
Implementing real-time/technical
applications using Lists, Tuples.
3A Items present in a library
3
3B Components of a car
3C Materials required for construction of a
building operations of list & tuples
Implementing real-time/technical applications
using Sets, Dictionaries.
4A Language
4
4B components of an automobile
4C Elements of a civil structure, etc.-
operations of Sets Dictionaries
Implementing programs using
Functions.
5 5A Factorial
5B largest number in a list
5C Area of shape
Implementing programs using Strings.
6A Reverse
6 6B Palindrome
6C Character count,
6D Replacing characters x`
Implementing programs using written
modules and Python Standard Libraries
7A Pandas
7 7B Numpy
7C Matplotlib
7D Scipy
Implementing real-time/technical
applications using File handling.
8 8A copy from one file to another
8B Word count
8C Longest word
Implementing real-time / technical
applications using Exception handling.
9 9A Divide by zero error
9B Voters age validity
9C Student mark range validation
10 Exploring Pygame tool
Developing a game activity using Pygame
like
11 11 A bouncing ball
11 B Car race
EX NO: 1A
EXCHANGE OF TWO VALUES
DATE:

AIM

To write a program for exchange values of two values.

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

The value of x after swapping:10


The value of y after swapping:5

RESULT

Thus the exchange of two values has been executed and verified successfully.
EX NO: 1B
CIRCULATE THE VALUE OF N VARIABLES
DATE:

AIM

To write a program for circulate the value of n variables

PROGRAM
no_of_terms = int(input("Enter number of values : "))
list1 = []

forval in range(0,no_of_terms,1):

ele = int(input("Enter integer : "))

[Link](ele)
print("Circulating the elements of list ", list1)

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

Circulating the elements of list [6, 7, 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: 1C
DISTANCE BETWEEN TWO POINTS
DATE:

AIM

To write an algorithm and program for Distance between two points.

ALGORITHM

Step1: Take a value from the user and store it in a variable n.


Step2: Use a for loop where the value of i ranges between the values of 1 and n.
Step3: Print the value of i and „+‟ operator while appending the value of i to a list.
Step 4: Then find the sum of elements in the list.
Step 5: Print „=‟ followed by the total sum.
Step 6: Exit.

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: 2A
NUMBER SERIES
DATE:

AIM

To write an algorithm and program for number series.

ALGORITHM

1. Take a value from the user and store it in a variable n.


2. Use a for loop where the value of i ranges between the values of 1 and n.
3. Print the value of i and „+‟ operator while appending the value of i to a list.
4. Then find the sum of elements in the list.
5. Print „=‟ followed by the total sum.
6. Exit.

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=" ")
[Link](i)
print("=",sum(a))
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: 2B
NUMBER PATTERN
DATE:

AIM

To write a python program for number pattern.

ALGORITHM

Step1: Start

Step2: Print the number pattern using for loop.

Step3: Inner for loop is used to print the pattern upto n values.

Step4: Print j+1 values till the end value.

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: 2C
PYRAMID PATTERN
DATE:

AIM

To write an algorithm and program for pyramid pattern.

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:3A
IMPLEMENTING REAL-TIME/TECHNICAL APPLICATIONS USING
LISTS ITEMS PRESENT IN A LIBRARY
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:3B
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

['Engine', 'battery', 'light', 'front axle', 'brakes']


['Engine', 'battery', 'light', 'alternator', 'front axle', 'radiator', 'brakes']
['Engine', 'battery', 'light', 'alternator', 'front axle', 'radiator', 'brakes', 'trunk', 'air filter']
['Engine', 'light', 'alternator', 'front axle', 'radiator', 'brakes', 'trunk', 'air filter']
['Engine', 'light', 'alternator', 'front axle']
['Engine', 'light', 'alternator', 'front axle', 'radiator', 'brakes', 'trunk', 'air filter', 'seat', 'window
frame', 'mirror']

RESULT

Thus the Components of a car has been executed and verified successfully
EX NO:3C
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

('Cement bags', 'sand', 'aggregates', 'bricks')


('Cement bags', 'sand', 'aggregates', 'bricks', 'steel bars', 'paint')
('Cement bags', 'sand', 'aggregates')
paint
4
2
sand
Cement bags
-1

RESULT

Thus the Construction of a building has been executed and verified successfully
EX NO:4A
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

Thus the Languages has been executed and verified successfully


EX NO:4B
COMPONENTS OF AUTOMOBILE
DATE:

AIM

To write a python program items present in library using list

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

set(['steering wheel', 'radiator', 'gear', 'tyre'])


set(['wheel', 'brake', 'sensor'])
set(['wheel', 'steering wheel', 'brake', 'gear', 'radiator', 'sensor', 'tyre'])
set(['wheel', 'brake', 'sensor', 'light'])

RESULT

Thus the Components of Automobile has been executed and verified successfully
EX NO:4C
ELEMENTS OF A CIVIL STRUCTURE
DATE:

AIM

To write a python program Elements of a Civil structure using Dictionary.

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

{1: 'foundation', 2: 'floor'}


{1: 'walls', 2: 'beams', 3: 'roof', 4: 'stair'}
foundation
roof
floor
{1: 'foundation', 2: 'cement'}
beams

RESULT

Thus the Elements of a Civil structure has been executed and verified successfully
EX NO:5A
FACTORIAL
DATE:

AIM

To write a program for factorial of 'n' numbers.

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

# single line to find factorial


return 1 if (n==1 or n==0) else n * factorial(n - 1);

# 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:5B
LARGEST NUMBER IN LIST
DATE:

AIM

To write a program for largest number in list.

PROGRAM

# printing the last element


def largest(list):
large= list[0]
for i in list:
if i>large:
large=i
return large

#list
list=[3, 9, 7, 3, 6, 5, 7, 24, 6]
print("largest in ",list,"is")
print(largest(list))

OUTPUT

Largest in [3, 9, 7, 3, 6, 5, 7, 24, 6] is


24

RESULT

Thus the program for largest number in list has been verified successfully.
EX NO:5C
AREA OF SHAPE
DATE

AIM

To write a program for area of shape.

PROGRAM

# Python program to find Area of a circle

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:6A
STRING REVERSE
DATE:

AIM

To write a program for string reverse operation.

PROGRAM

defreverse(s):
str=""
fori ins:
str=i +str
returnstr

s ="Pavithra"

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


print(s)

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


print(reverse(s))

OUTPUT

The original string is: Pavithra


The reversed string (using loops) is: arhtivaP

RESULT

Thus the program for string reverse has been verified successfully.
EX NO:6B
STRING PALINDROME
DATE:

AIM

To write a program for string palindrome operation.

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:6C
COUNT THE CHARACTERS IN STRING
DATE:

AIM
To write a program for count the characters in string operation.

PROGRAM

test_string ="Geeksforgeeks is best Computer Science Portal"

# printing original string


print("The original string is : "+test_string)

# 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

The original string is :Geeksforgeeks is best Computer Science Portal


The number of words in string are : 6
The number of words in string are : 45

RESULT

Thus the program for count the characters in string has been verified successfully.
EX NO:6D
REPLACE CHARACTERS
DATE:

AIM

To write a program for replace characters in string operation.

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

The original string is:


This is [Link]. Here, you can read python tutorials for free.
Output String is:
ThIs Is [Link]. Here, you can read python tutorIals for free.

RESULT

Thus the program for replace characters in string has been verified successfully.
EX NO:7A
PANDAS
DATE:

AIM

To write a program for replace characters in string operation.

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

Thus the program for pandas has been verified successfully.


EX NO:7B
NUMPY
DATE:

AIM

To write a program for replace characters in string operation.

PROGRAM

importnumpy as np

# Create the following rank 2 array with shape (3, 4)

a = [Link]([[1,2,3,4], [5,6,7,8], [9,10,11,12]])

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
Thus the program for numpy has been verified successfully.
EX NO:7C
MATPLOT
DATE:
AIM

To write a program for Matplot.

PROGRAM

[Link] as plt

# Data labels, sizes, and colors are defined:

labels = 'Broccoli', 'Chocolate Cake', 'Blueberries', 'Raspberries'


sizes = [30, 330, 245, 210]
colors = ['green', 'brown', 'blue', 'red']
# Data is plotted:
[Link](sizes, labels=labels, colors=colors)
[Link]('equal')
[Link]('Pie Plot')
[Link]()

OUTPUT

RESULT

Thus the program for Matplot has been verified successfully.


EX NO:7D
SCIPY
DATE:

AIM

To write a program for Scipy.

PROGRAM

[Link] import root


from math import cos

defeqn(x):
return x + cos(x)

myroot = root(eqn, 0)

print(myroot.x)

OUTPUT

[-0.73908513]

RESULT

Thus the program for scipy has been verified successfully


EX:NO: 8A IMPLEMETING REAL TIME APPLICATION USING FILE HANDLING
COPY FROM ONE FILE TO ANOTHER FILE
DATE:
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()

fileHandle = open(sFile, "r")


texts = [Link]()
[Link]()

fileHandle = open(tFile, "w")


for s in texts:
[Link](s)
[Link]()

print("\nFile Copied Successfully!")


OUTPUT

RESULT

Thus the given program was executed successfully.


EX:NO: 8B
WORD COUNT
DATE:

AIM

To write a python program for count the words in a file.

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)
Step5: Print the total number of words in a file.
Step6: Stop.

PROGRAM
number_of_words = 0

# Opening our text file in read only


# mode using the open() function
with open('[Link]','r') as file:
# Reading the content of the file
# using the read() function and storing
# them in a new variable
data = [Link]()
# Splitting the data into separate lines
# using the split() function
lines = [Link]()
# Adding the length of the
# lines in our number_of_words
# variable
number_of_words += len(lines)
# Printing total number of words
print(number_of_words)

OUTPUT

RESULT
Thus, the python program to count the words in file has been created and executed
successfully.
EX:NO: 8C
LONGEST WORD
DATE:

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,
return[word for word in words iflen(word)==max_len]
Step6: Print the longest word in a file.
Step7. Stop.
PROGRAM

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.
EX:NO: 9A IMPLEMETING REAL TIME APPLICATION USING EXCEPTION HANDLING
DATE: DIVIDE BY ZERO

AIM

To write a python program for exception handling to perform divide by zero.

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: "))

result = num1 / num2

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
divisions by zero

RESULT
Thus the python program for exception handling to perform divide by zero has been created and
executed successfully.
EX:NO: 9B
VOTERS AGE VALIDITY
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
created and executed successfully.
EX:NO: 9C
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
Trace back (most recent call last):
File "<string>", line 4, in <module>
Value Error: 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: 10
EXPLORING PYGAME TOOL
DATE:

AIM
To develop the games using python installation package by exploring Pygame tool.

EXPLORING PYGAME 1 - DISCOVERING THE LIBRARY


Game development is one of the most common reasons to start to study programming.
The pygame library as tool and I will start by the most basic principles of game development
until the creation of a single player pong like game.

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

After that install pygame at your virtualenv:


$ pip install pygame
Or system wide:
$ sudo pip install 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:
-*- coding: utf-8 -*-

import time

importpygame

[Link]()

screen = [Link].set_mode([640, 480])

[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.
At [Link].set_mode we create an area for the game window at the size of
640x480 pixels, followed by [Link].set_caption were we set the value “Hello World” to
our window title.
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.
The command [Link] represents an important concept to pygame and game
development itself. When we use commands to draw at the screen, we are actually drawing a
virtual surface at the memory that represents a portion of our actual screen. To make that
drawing visible to the user we need to send it to the actual screen, and we do it in these two
separate steps to prevent from displaying incomplete frames to the user. It is like drawing at a
board and then “flipping it” to people see what we drew.
And then, to finish the command sleep from the library time makes the program to wait 5
seconds before finish the execution. Otherwise, the program would close before we see the
result.

RESULT
Thus the Pygame tool for development of gaming application using python has been explored
and developed successfully.
EX NO:11 A
DEVELOPING A GAME ACTIVITY USING PYGAME LIKE BOUNCING BALL
DATE :

AIM
To write a python program to simulate bouncing ball using pygame tool.

ALGORITHM

Step 1: Import pygame module.


Step 2: Call [Link]() to initiate all imported pygame module.
Step 3: Set the screen size in terms of pixels using [Link].set_mode((400, 300)
Step [Link] there is any event in pygame queue.
a. Get the event from the pygame queue
b. If event types is [Link] then set done=true
Step 5. Else, Draw the circle update the screen display with new circle to bring
bouncing effect.
Step 6. Call [Link]() to uninitialized all the pygame modules.

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]()
[Link](screen, (255,255,255), [150, 95], 10, 0)
[Link]()
[Link](screen, (0,0,0), [150, 95], 10, 0)
[Link]()
[Link](screen, (255,255,255), [200, 130], 10, 0)
[Link]()
[Link](screen, (0,0,0), [200, 130], 10, 0)
[Link]()
[Link](screen, (255,255,255), [250, 150], 10, 0)
[Link]()
[Link]()
for event in [Link]():
[Link] == QUIT:
[Link]()
[Link]()

OUTPUT

RESULT

Thus, the python program for bouncing ball in Pygame has been executed
successfully.
EX NO:11 B
DEVELOPING A GAME ACTIVITY USING PYGAME LIKE CAR GAME
DATE

AIM

To write a python program to simulate car game using Pygame tool.

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

importpygame, random, sys ,os,time


[Link] 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():
[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
for event in [Link]():
[Link] == QUIT:
terminate()
[Link] == KEYDOWN:
[Link] == ord('z'):
reverseCheat = True
[Link] == ord('x'):
slowCheat = True
[Link] == K_LEFT or [Link] == ord('a'):
moveRight = False
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] == K_LEFT or [Link] == ord('a'):


moveLeft = False
[Link] == K_RIGHT or [Link] == ord('d'):
moveRight = False
[Link] == K_UP or [Link] == ord('w'):
moveUp = False
[Link] == K_DOWN or [Link] == ord('s'):
moveDown = False

# Add new baddies at the top of the screen


if not reverseCheat and not slowCheat:
baddieAddCounter += 1
ifbaddieAddCounter == ADDNEWBADDIERATE:
baddieAddCounter = 0
baddieSize =30
newBaddie = {'rect': [Link]([Link](140, 485), 0 - baddieSize, 23, 47),
'speed': [Link](BADDIEMINSPEED, BADDIEMAXSPEED),
'surface':[Link]([Link](sample), (23, 47)),
}
[Link](newBaddie)
sideLeft= {'rect': [Link](0,0,126,600),
'speed': [Link](BADDIEMINSPEED, BADDIEMAXSPEED),
'surface':[Link](wallLeft, (126, 599)),
}
[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 Car game using Pygame has been executed successfully.
MINI PROJECT
SOURCE CODE

print("You win!", player, "covers", computer)


player_score+=1
elif player == "Scissors":
if computer == "Rock":
print("You lose...", computer, "smashes", player)
cpu_score+=1
else:
print("You win!", player, "cut", computer)
player_score+=1
elif player=='E':
print("Final Scores:")
print(f"CPU:{cpu_score}")
print(f"Plaer:{player_score}")
break
else:
print("That's not a valid play. Check your spelling!")
computer = [Link](choices)

OUTPUT

Tie!
Rock, Paper or Scissors?Paper
Tie!
Rock, Paper or Scissors?Scissors
You win! Scissors cut Paper
Rock, Paper or Scissors?

You might also like