GE3171 – Problem Solving and Python Programming Laboratory
Experiment 1: Identification and solving of simple real life or scientific or technical
problems and developing flow charts for the same. (Electricity Billing, Retail shop billing,
Sin series, weight of motorbike, Weight of a steel bar, compute Electrical Current in Three
Phase AC Circuit, etc.)
Aim:
Identification and solving of simple real life or scientific or technical problems
(Electricity Billing, Retail shop billing, Sin series) and developing flow charts for the same.
Flowchart:
1a. Electricity Billing – Flowchart
- Available in Book (Pg. No. 204)
1b. Sin Series – Flowchart
- Available in Book (Pg. No. 206)
1c. Retail shop Billing – Flowchart
Conclusion:
Thus the identification and solving of simple real life or scientific or technical problems
(electricity billing, retail shop billing, and sin series) and developing flow charts has been
developed and verified.
Prepared by: Mr. Umapathy.M AP-CSE ,TKEC Page 1 of 25
GE3171 – Problem Solving and Python Programming Laboratory
Experiment 2: Python programming using simple statements and expressions (exchange the
values of two variables, circulate the values of n variables, distance between two points).
Aim:
To write a Python program using simple statements and expressions (exchange the
values of two variables, circulate the values of n variables, distance between two points).
2a. Exchange the values of two variables
Algorithm:
1. Start
2. Read the variable a,b,temp.
3. temp=a;a=b;b=temp;
4. Print the value a,b.
5. Stop
Program:
P = int( input("Enter value for P: "))
Q = int( input("Enter value for Q: "))
# To swap the value of two variables
# we will user third variable which is a temporary variable
temp_1 = P
P=Q
Q = temp_1
print ("The Value of P after swapping: ", P)
print ("The Value of Q after swapping: ", Q)
Output:
Enter value for P: 2
Enter value for Q: 3
The Value of P after swapping: 3
The Value of Q after swapping: 2
2b. Circulate the value of 4 variables
Algorithm:
1. Start
2. Read a,b,c,d
3. t=a, a=d,d=c,c=b,b=t
4. Print the value of a,b,c,d
5. Stop
Program:
a,b,c,d=10,20,30,40
print("Before circulating")
print("a = ",a)
print("b = ",b)
print("c = ",c)
print("d = ",d)
t=a
a=d
d=c
c=b
Prepared by: Mr. Umapathy.M AP-CSE ,TKEC Page 2 of 25
GE3171 – Problem Solving and Python Programming Laboratory
b=t
print("After circulating")
print("a = ",a)
print("b = ",b)
print("c = ",c)
print("d = ",d)
Output:
a= 40
b = 10
c = 20
d = 30
2c. Distance Between Two Points
Algorithm:
Step 1: Start
Step 2: Enter the values of x1, x2 ,y1, y2
Step 3: Calculate the distance between two points using formula√( 2 − 1)2 + ( 2 − 1)^2
Step 4: Display the result
Step 5: Stop
Program:
print("Enter the first point")
x1=int(input("Enter the value for x1 "))
y1=int(input("Enter the value for y1 "))
print("Enter the second point")
x2=int(input("Enter the value for x2 "))
y2=int(input("Enter the value for y2 "))
a=(x1-x2)**2
b=(y1-y2)**2
distance=(a+b)**0.5
print("Distance = ",distance)
Output:
Enter the first point
Enter the value for x1 12
Enter the value for y1 14
Enter the second point
Enter the value for x2 15
Enter the value for y2 16
Distance = 3.605551275463989
Conclusion:
Thus the above Python programs using simple statements and expressions (exchange
the values of two variables, circulate the values of n variables, distance between two points)
has been executed and verified.
Prepared by: Mr. Umapathy.M AP-CSE ,TKEC Page 3 of 25
GE3171 – Problem Solving and Python Programming Laboratory
Experiment3: Scientific problems using Conditionals and Iterative loops. (Number series,
Number Pattern, Pyramid pattern)
Aim:
To write a Python program for scientific problems using Conditionals and Iterative
loops (Number series, Number Pattern, Pyramid pattern).
3a. Number series (Sumof1ton=1+2+3+…..+n)
Algorithm:
Step 1: Start.
Step 2: Read n
Step 3: Initialize Sum=0, i=1
Step 4: While i<=n
Step 4.1: Sum=Sum+i
Step 4.2: i=i+1
Step 5: Print Sum
Step 6: Stop.
Program:
n=int(input("Enter the Number: "))
sum=0
i=1
while i<=n:
sum=sum+i
i=i+1
print("Sum of Numbers(1 to ",n,") is : ",sum)
Output:
Enter the Number: 10
Sum of Numbers (1 to 10 ) is : 55
3b. Pyramid Pattern and Number Pattern
Algorithm:
1. Start
2. Accept the number of rows from a user using the input () function to decide the size of
a pattern.
3. Next, write an outer loop to Iterate the number of rows using a for
loop and range() function.
4. Next, write the inner loop or nested loop to handle the number of columns. The internal
loop iteration depends on the values of the outer loop.
5. Use the print () function in each iteration of nested for loop to display the symbol or
number of a pattern (like a star (asterisk *) or number).
6. Add a new line using the print() function after each iteration of the outer loop so that
the pattern display appropriately
7. Stop
Prepared by: Mr. Umapathy.M AP-CSE ,TKEC Page 4 of 25
GE3171 – Problem Solving and Python Programming Laboratory
Program (Pyramid Pattern):
n=int(input("Enter the Number: "))
for i in range(0, n):
for j in range(0, i+1):
print("* ",end="")
print("\r")
Output:
Enter the Number: 5
*
**
***
****
*****
Program (Number Pattern):
n=int(input("Enter the Number: "))
for i in range(0, n):
for j in range(0, i+1):
print("2 ",end="")
print("\r")
Output:
Enter the Number: 5
2
22
222
2222
22222
Conclusion:
Thus the above Python programs for scientific problems using Conditionals and
Iterative loops (Number series, Number Pattern, Pyramid pattern) has been executed and
verified.
Prepared by: Mr. Umapathy.M AP-CSE ,TKEC Page 5 of 25
GE3171 – Problem Solving and Python Programming Laboratory
Experiment4: Implementing real-time/technical applications using Lists, Tuples. (Items
present in a library/Components of a car–operations of list & tuples).
Aim:
To write a Python programs to implement real-time/technical application (Items
present in a library) using Lists and Tuples.
4a. Items present in a Library using List
Algorithm:
Step 1: Start
Step 2: Initialize the Value in the list
Step 3: find the length of list
Step 4: Read the element to insert in a list
Step 5: Read the element to POP in a list
Step 6: Read the element to Sort in a list
Step 7: Stop
Program:
books=['C', 'C++','Web Technology','PYTHON','Maths']
print("Currently No of books available: ",len(books))
pos1 = int(input("Enter the pos to insert: "))
element = input("Enter the element to insert: ")
books.insert(pos1,element)
print("After insertion updated book list is","\n",books)
print("Currently No of books available: ",len(books))
pos2 = int(input("Enter the pos to delete: "))
books.pop(pos2)
print("After deletion updated list is","\n",books)
print("Currently No of books available: ",len(books))
books.sort()
print("After sorting the book title", books)
Output:
Currently No of books available: 5
Enter the pos to insert: 2
Enter the element to insert: Networks
After insertion updated book list is
['C', 'C++', 'Networks', 'Web Technology', 'PYTHON', 'Maths']
Currently No of books available: 6
Enter the pos to delete: 1
After deletion updated list is
['C', 'Networks', 'Web Technology', 'PYTHON', 'Maths']
Currently No of books available: 5
After sorting the book title ['C', 'Maths', 'Networks', 'PYTHON', 'Web Technology']
Prepared by: Mr. Umapathy.M AP-CSE ,TKEC Page 6 of 25
GE3171 – Problem Solving and Python Programming Laboratory
4b. Items present in a Library using Tuple
Algorithm:
Step 1: Start
Step 2: Initialize the Value in the Tuple
Step 3: find the length of Tuple
Step 4: Print the length of the book by using len ()
Step 5: Print the Maximum price of the book by using max ()
Step 6: Print the Minimum price of the book by using min ()
Step 7: Stop
Program:
books=('C', 'C++', 'JAVA', 'C')
bookPrice=(1200,500, 1250)
print("Currently No of books available: ",len(books))
print("Maximum Book Price is ",max(bookPrice))
print("Minimum Book Price is ",min(bookPrice))
print("Enter book name to find how many copies of specified book available in the library")
countBook =input()
print(books.count(countBook))
Output:
Currently No of books available: 4
Maximum Book Price is 1250
Minimum Book Price is 500
Enter book name to find how many copies of specified book available in the library
C
2
Conclusion:
Thus the above Python programs to implement real-time/technical application (Items
present in a library) using Lists and Tuples has been executed and verified.
Prepared by: Mr. Umapathy.M AP-CSE ,TKEC Page 7 of 25
GE3171 – Problem Solving and Python Programming Laboratory
Experiment5: Implementing real-time/technical applications using Sets, Dictionaries.
(Language, components of an automobile, Elements of a civil structure, etc. - operations of
Sets & Dictionaries).
Aim:
To write a Python program to implement real-time/technical application using Sets and
Dictionaries for Components of an Automobile.
5a. Operations of Dictionaries
Algorithm:
Step 1: Start
Step 2: Create a Dictionary called auto with components of automobile.
Step 3: Use len( ) method to print the length of the dictionary.
Step 4: Use get( ) method to get the value of any key.
Step 5: Use keys( ), to print the keys.
Step 6: Use values( ), to print the values.
Step 7: Use items( ), to print items.
Step 8: Stop
Program:
auto={'Engine':'V Engine','Clutch':'Diaphragm','Chassis':'Tubular','Gearbox':'Synchromesh'}
print("Length is: ",len(auto))
print("Type of Engine is: ",auto["Engine"])
x=auto.get("Clutch")
print("Type of Clutch is: ",x)
k=auto.keys()
print("The Keys are: ",k)
auto["Brakes"]="Drum Brakes"
print("The Keys are: ",k)
v=auto.values()
print("The Values are: ",v)
item=auto.items()
print("Items are: ")
print(item)
Output:
Length is: 4
Type of Engine is: V Engine
Type of Clutch is: Diaphragm
The Keys are: dict_keys(['Engine', 'Clutch', 'Chassis', 'Gearbox'])
The Keys are: dict_keys(['Engine', 'Clutch', 'Chassis', 'Gearbox', 'Brakes'])
Prepared by: Mr. Umapathy.M AP-CSE ,TKEC Page 8 of 25
GE3171 – Problem Solving and Python Programming Laboratory
The Values are: dict_values(['V Engine', 'Diaphragm', 'Tubular', 'Synchromesh', 'Drum
Brakes'])
Items are:
dict_items([('Engine', 'V Engine'), ('Clutch', 'Diaphragm'), ('Chassis', 'Tubular'), ('Gearbox',
'Synchromesh'), ('Brakes', 'Drum Brakes')])
5b. Operations of Sets
Algorithm:
Step 1: Start
Step 2: Create a Set called auto1 and auto2 with components of automobile.
Step 3: Use add( ) method, to add an Item.
Step 4: Use remove( ) method, to remove an Item.
Step 5: Use union( ) method, to join two sets.
Step 6: Use pop( ) method, to remove the first element.
Step 7: Stop.
Program:
auto1={"Engine","Clutch","Gearbox","Engine"}
auto2={"V Engine","Diaphragm","Synchromesh"}
print("Items are: ")
print(auto1) #Duplicate values will be ignored
print(auto2)
auto1.add("Axle")
print("After Addition Items are: ")
print(auto1)
auto1.remove("Engine")
print("After Removal Items are: ")
print(auto1)
auto=auto1.union(auto2)
print("After Union: ")
print(auto)
auto.pop()
print("After Pop: ")
print(auto)
Prepared by: Mr. Umapathy.M AP-CSE ,TKEC Page 9 of 25
GE3171 – Problem Solving and Python Programming Laboratory
Output:
Items are:
{'Engine', 'Gearbox', 'Clutch'}
{'Diaphragm', 'Synchromesh', 'V Engine'}
After Addition Items are:
{'Axle', 'Engine', 'Gearbox', 'Clutch'}
After Removal Items are:
{'Axle', 'Gearbox', 'Clutch'}
After Union:
{'Diaphragm', 'V Engine', 'Gearbox', 'Axle', 'Synchromesh', 'Clutch'}
After Pop:
{'V Engine', 'Gearbox', 'Axle', 'Synchromesh', 'Clutch'}
Conclusion:
Thus the above Python programs to implement real-time/technical application using
Sets and Dictionaries for Components of an Automobile has been executed and verified.
Prepared by: Mr. Umapathy.M AP-CSE ,TKEC Page 10 of 25
GE3171 – Problem Solving and Python Programming Laboratory
Experiment6: Implementing programs using Functions (Factorial, largest number in a list,
area of shape).
Aim:
To write a Python program to implement the concept of functions for Factorial, largest
number in a list, area of shape.
6a. Find the Factorial Value of a Number
Algorithm:
Step 1:Start
Step 2:Read the number
Step 3:If n<0 then print factorial does not exist
Step 4: Elseif n==0 then print the factorial of 0 is 1
Step 5: Else call factorial(n)
Step 6: Stop
Algorithm for Factorial(n) function:
Step 1: If n==1 then return n
Step 2: Else F=n*factorial(n-1)
Step 3: return F
Program:
def factorial(n):
fact=1
i=1
while i<=n:
fact=fact*i
i=i+1
print("Factorial Value of",n,"is :",fact)
n=int(input("Enter the Number to find the Factorial Value: "))
factorial(n)
Output:
Enter the Number to find the Factorial Value: 5
Factorial Value of 5 is: 120
Prepared by: Mr. Umapathy.M AP-CSE ,TKEC Page 11 of 25
GE3171 – Problem Solving and Python Programming Laboratory
6b. Largest Number in a List
Algorithm:
Step 1: Start
Step 2: Create a list of numbers.
Step 3: Use len( ), to obtain the length of the list.
Step 4: Use sort( ), to sort in ascending order.
Step 5: Print the largest number in a list.
Step 6: Stop.
Program:
list=[12,45,67,33,10,98,78,90,55]
x=len(list)
list.sort()
print("Numbers in List are: ")
print(list)
print("The Largest Number in the List is: ")
print(list[x-1])
Output:
Numbers in List are:
[10, 12, 33, 45, 55, 67, 78, 90, 98]
The Largest Number in the List is:
98
6c. Area of a Shape
Algorithm:
Step 1: Start
Step 2: Read the shape you want to calculate the area.
Step 3: Define a function calculate_area( ), to calculate areas of various shapes.
Step 4: Print the area.
Step 5: Stop.
Program:
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("The area of rectangle is: ",rect_area)
elif name == "square":
Prepared by: Mr. Umapathy.M AP-CSE ,TKEC Page 12 of 25
GE3171 – Problem Solving and Python Programming Laboratory
s = int(input("Enter square's side length: "))
sqt_area = s * s
print(" 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("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("The area of triangle is: ",circ_area)
else:
print("Sorry! This shape is not available")
print("Calculate Shape Area")
shape_name=input("Enter the name of shape whose area you want to find: ")
calculate_area(shape_name)
Output:
Calculate Shape Area
Enter the name of shape whose area you want to find: rectangle
Enter rectangle's length: 2
Enter rectangle's breadth: 5
The area of rectangle is: 10
Calculate Shape Area
Enter the name of shape whose area you want to find: circle
Enter circle's radius length: 5
The area of triangle is: 78.5
Calculate Shape Area
Enter the name of shape whose area you want to find: triangle
Enter triangle's height length: 4
Enter triangle's breadth length: 5
The area of triangle is: 10.0
Calculate Shape Area
Enter the name of shape whose area you want to find: square
Enter square's side length: 5
The area of square is: 25
Prepared by: Mr. Umapathy.M AP-CSE ,TKEC Page 13 of 25
GE3171 – Problem Solving and Python Programming Laboratory
Conclusion:
Thus the above Python programs to implement the concept of functions for Factorial,
largest number in a list, area of shape has been executed and verified.
Prepared by: Mr. Umapathy.M AP-CSE ,TKEC Page 14 of 25
GE3171 – Problem Solving and Python Programming Laboratory
Experiment7: Implementing programs using Strings. (Reverse, Palindrome, Character count,
replacing characters).
Aim:
To write a Python program to implement programs using Strings (Reverse, Palindrome,
Character count, Replacing characters).
Algorithm:
Step 1: Start
Step 2: Use slice operator [::-1] to reverse the string.
Step 3: Use replace( ),to replace a substring. Step
4: Compare strings and print the result. Step 5:
Stop.
Program:
txt="Computer Science"[::-1]
print(txt)
print("Number of Occurrences of Character e: ",txt.count("e"))
t="Computer Science"
x=t.replace("Computer","Social")
print(x)
t="radar"
b=(t==t[::-1])
if b:
print("Radar is a Palindrome String")
else:
print("Not Palindrome")
Output:
Reverse of the String:
ecneicS retupmoC
Number of Occurrences of Character e: 3
Social Science
Radar is a Palindrome String
Conclusion:
Thus the above python program to implement the concept of Strings (Reverse,
Character Count, Replacing characters and Palindrome) has been executed and verified.
Prepared by: Mr. Umapathy.M AP-CSE ,TKEC Page 15 of 25
GE3171 – Problem Solving and Python Programming Laboratory
Experiment 8: Implementing programs using written modules and Python Standard Libraries
(pandas, numpy. Matplotlib, scipy).
Aim:
To write a Python program to implement the concept of Modules and Python Standard
Libraries (pandas, numpy, Matplotlib, scipy).
8a. Program Using Modules
Algorithm:
Step 1: Start
Step 2: Create a module and save using .py extension.
Step 3: Use the created module, by using import statement.
Step 4: Stop
Program:
#Save the below code as calc.py
def add(x, y):
return (x+y)
def subtract(x, y):
return (x-y)
#Save this program in another name and run
import calc
print("Addition: ",calc.add(10, 2))
print("Subtraction: ",calc.subtract(45,22))
Output:
Addition: 12
Subtraction: 23
8b. Python Standard Libraries (pandas, numpy, Matplotlib, scipy)
Program:
import pandas as pd
import matplotlib.pyplot as plt
data = {"Pass%": [90, 70, 50], "Students_Count": [20, 50, 30]}
df = pd.DataFrame(data, index = ["Test1", "Test2", "Test3"])
df.plot(kind = 'bar', x = 'Pass%', y = 'Students_Count')
plt.show()
Prepared by: Mr. Umapathy.M AP-CSE ,TKEC Page 16 of 25
GE3171 – Problem Solving and Python Programming Laboratory
Output:
Conclusion:
Thus the above Python program to implement the concept of Modules and Python
Standard Libraries (pandas, numpy, Matplotlib, scipy) has been executed and verified.
Prepared by: Mr. Umapathy.M AP-CSE ,TKEC Page 17 of 25
GE3171 – Problem Solving and Python Programming Laboratory
Experiment 9: Implementing real-time/technical applications using File handling. (Copy from
one file to another, word count, longest word).
Aim:
To write a Python program to implement the real-time/technical applications using File
Handling (Copy from one file to another, word count, longest word).
Algorithm:
Step 1: Start
Step 2: Using open( ), open a file.
Step 3: Using read( ), read the content of a file.
Step 4: Using close( ), close the opened file.
Step 5: Stop
9a. Copy from one File to another
Program:
import shutil
f1=input("Enter Source File Name: ")
f2=input("Enter Destination File Name: ")
shutil.copyfile(f1,f2)
print("File Copied Successfully")
c=open(f2,"r")
print(c.read( ))
c.close( )
Output:
Enter source file name: first.txt
Enter destination file name: second.txt
File copied successfully
Given two text files, the task is to write a Python program to copy contents of the first file into the
second file.
The text files which are going to be used are second.txt and first.txt
9b. Word Count
Program:
file=open("first.txt", "r")
data=file.read( )
print("Content of first.txt file :")
print(data)
words=data.split( )
print("Number of words in the text file is:", len(words))
Prepared by: Mr. Umapathy.M AP-CSE ,TKEC Page 18 of 25
GE3171 – Problem Solving and Python Programming Laboratory
Output:
Content of first.txt file:
Given two text files, the task is to write a Python program to copy contents of the first file into the
second file.
The text files which are going to be used are second.txt and first.txt
Number of words in the text file is: 36
9c. Longest Word in a File
Program:
def long1(file):
with open(file,"r") as f:
words=f.read( ).split( )
ma=len(max(words, key=len)
return [word for word in words if len(word)==ma]
print(long1("sample.txt"))
#sample.txt file content
Agriculture Engineering
Electrical and Electronics Engineering
Electronics and Communication Engineering
Output:
Longest word in the file is:
['Communication']
Conclusion:
Thus the above Python program to implement the real-time/technical applications using File
Handling (Copy from one file to another, word count, longest word) has been executed and
verified.
Prepared by: Mr. Umapathy.M AP-CSE ,TKEC Page 19 of 25
GE3171 – Problem Solving and Python Programming Laboratory
Experiment 10: Implementing real-time/technical applications using Exception handling. (Divide
by zero error, voter’s age validity, student mark range validation).
Aim:
To write a Python program to implement real time / technical applications using Exception
handling (Divide by Zero error, voter’s age validity).
10a. Divide by Zero Error
Program:
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
except Exception as e:
print("Can't divide by zero")
print(e)
else:
print(“ This is Else block, No Exception Caught")
Output:
Enter a: 12
Enter b: 0
Can't divide by zero
Division by zero
10b. Voter’s Age Validity
Program:
try:
age=int(input("Enter your Age: "))
if age>=18:
print("Eligible to Vote")
else:
print("Not eligible to Vote")
except ValueError:
print("Age must be a valid Number")
except IOError:
print("Enter correct value")
except:
print("An Error occured")
Prepared by: Mr. Umapathy.M AP-CSE ,TKEC Page 20 of 25
GE3171 – Problem Solving and Python Programming Laboratory
Output:
Enter your Age: 25
Eligible to Vote
>>>
Enter your Age: 14
Not eligible to Vote
>>>
Enter your Age: 2f
Age must be a valid Number
>>>
Conclusion:
Thus the above Python program to implement real time / technical applications using
Exception handling (Divide by Zero error, voter’s age validity) has been executed and verified.
Prepared by: Mr. Umapathy.M AP-CSE ,TKEC Page 21 of 25
GE3171 – Problem Solving and Python Programming Laboratory
Experiment 11: Exploring Pygame tool
Aim:
To write a Python program to explore Pygame Tool.
Algorithm:
Step 1: Start.
Step 2: Import and Initialize Pygame. The command pygame.init() starts all modules that
need initialization inside pygame.
Step 3: Set screen size using pygame.display.set_mode to create an area for the game
window at the size of 500 X 500 pixels.
Step 4: Command fill is used to fill the screen color.
Step 5: Command pygame.display.flip is used to make the drawing visible to the user.
Step 6: Stop.
Program:
import pygame
pygame.init()
screen = pygame.display.set_mode([500, 500])
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((0,0,0))
pygame.draw.circle(screen, (255, 255, 255), (250, 250), 75)
pygame.display.flip()
pygame.quit()
Prepared by: Mr. Umapathy.M AP-CSE ,TKEC Page 22 of 25
GE3171 – Problem Solving and Python Programming Laboratory
Output:
Conclusion:
Thus the above Python program to explore Pygame tool has been executed and verified.
Prepared by: Mr. Umapathy.M AP-CSE ,TKEC Page 23 of 25
GE3171 – Problem Solving and Python Programming Laboratory
Experiment 12: Developing a game activity using Pygame like bouncing ball.
Aim:
To write a Python program to develop a game activity using Pygame like bouncing ball.
Algorithm:
Step 1: Import and Initialize Pygame.
Step 2: Set screen size, background color and caption.
Step 3: Load the moving object and set the rectangle area covering the image.
Step 4: Set speed of the moving object.
Step 5: Make ball movement continuity.
Step 6: Fill the background color and blit the screen.
Step 7: Make image visible.
Step 8: Stop.
Program:
import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
import sys, pygame
from pygame.locals import *
pygame.init()
speed = [1, 1]
color = (255, 250, 250)
width = 550
height = 300
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Pygame bouncing ball")
ball = pygame.image.load(“Ball.png")
rect_boundry = ball.get_rect()
while 1:
for event in pygame.event.get():
rect_boundry = rect_boundry.move(speed)
if rect_boundry.left < 0 or rect_boundry.right > width:
speed[0] = -speed[0]
if rect_boundry.top < 0 or rect_boundry.bottom > height:
speed[1] = -speed[1]
screen.fill(color)
screen.blit(ball, rect_boundry)
pygame.display.flip()
if event.type == QUIT:
pygame.quit()
sys.exit()
Prepared by: Mr. Umapathy.M AP-CSE ,TKEC Page 24 of 25
GE3171 – Problem Solving and Python Programming Laboratory
Output
Conclusion:
Thus the above Python program to develop a game activity using Pygame like bouncing ball
has been developed and verified.
Prepared by: Mr. Umapathy.M AP-CSE ,TKEC Page 25 of 25