Ge3171 PSPP Lab Manual Final
Ge3171 PSPP Lab Manual Final
NATTRAJA
COLLEGE OF ENGINEERING & TECHNOLOGY
(Affiliated to Anna University, Chennai)
KUMARAPALAYAM-638 183.
LIST OF EXPERIMENTS
ii
Programs Using modules and Python Standard Libraries
a) Pandas
b) Numpy
8. c) Matplotlib
d) Scipy
Programs using File Handling.
a) Copy from one file to another,
9. b) Word count
c) Longest word
Programs Using Exception handling.
a) Divide by zero error
10. b) Voter’s age validity
c) Student mark range validation
iii
CONTENTS
Page
S.No. Date Name of the Experiment Marks Sign
No.
1 Developing flow charts
A. Electricity Billing
B. Retail Shop Billing
C. Sin Series
D. Weight of a Motorbike
E. Weight of a Steel Bar
F. Compute Electrical Current in Three Phase
AC Circuit
2 Programs Using Simple Statements
A. Number Series
B. Number Patterns
C. Pyramid Pattern
A. Operations of Lists (Items present in a
4 library/Components of acar/ Materials required
for construction of a building)
B. Operations of Lists and Tuples (Items
present in a library/Components of a car/
Materials required for construction of a building)
A. Operations of Sets (Language,
5 components of an automobile,
Elementsofa civil structure, etc)
B. Operations of Dictionaries (Language,
components of an automobile,Elements of a civil
structure, etc)
6 Programs Using Functions
A. Factorial of a Number
B. Largest Number in a list
C. Area of Shape
iv
7 Programs using Strings.
A. Reversing a String
B. Checking Palindrome in a String
B. Word count
C. Longest word
v
Ex.No 1.A
Developing flow charts for Electricity Billing
Date:
Aim:
To write a algorithm and draw flowchart for Electric Billing.
Algorithm:
Step3: Check n<=100. If yes, then print amt =0. Then go to step7.
Step4: Check n<=200 is True, then calculate amt= (n-100)*1.5 and go to step 7.If no go to step5
Step5: Check n<=500.If yes, then calculate amt=200+ (n-200)*3 and go to step7.If no go to step6
1
Flowchart:
Start
Read units
<=200
Amount =100*0
Amount= (100*0)+(200-
100)*3.5+(500-200)*4.6
+(unit-500)*6.6
Amount =(100*0)+ Amount =
(unit-100)*1.5 (100*0)+ (200-100)*2+
(unit-200)*3
Print Amount
Stop
Result:
2
Ex.No 1.B
Developing flow charts for Retail Shop Billing
Date:
Aim:
To write a algorithm and draw flowchart for Retail Shop Billing.
Algorithm:
3
Flowchart:
Start
Tax=0.18
Display Quantities
Read Quantities
stop
Result:
4
Ex.No 1.C
Developing flow charts for Sin Series
Date:
Aim:
To write a algorithm and draw flowchart for Retail Shop Billing.
Algorithm:
Step2: Read x, n
5
Flowchart:
Start
Read x, n
x=x*3.14159/180;
t=x;
sum=x;
i=1;i<=n; i++
t= (t*(-1)*x*x)/(2*i*(2*i+1));
sum= sum+t;
stop
Result:
6
Ex.No 1.D
Developing flow charts for Weight of a Motorbike
Date:
Aim:
To write a algorithm and draw flowchart for Retail Shop Billing.
Algorithm:
7
Flowchart:
Start
Initialise ADC=0
No Is it
digitally
clear?
yes
Display it on LCD
Stop
Result:
8
Ex.No 1.E
Developing flow charts for Weight of a Steel Bar
Date:
Aim:
To write a algorithm and draw flowchart for Retail Shop Billing.
Algorithm:
9
Flowchart:
Start
Input l &r
den =7800
wt =(math .pi*r*l*den)/10000
Print (wt)
stop
Result:
10
Ex. No 1.F
Aim:
To write a algorithm and draw flowchart for Retail Shop Billing.
Algorithm:
Step4: Print VA
11
Flowchart:
Start
VA=√3*Vline*Aline
Print VA
Stop
Result:
12
Ex. No 2.A
Exchange the values of two variables using Simple Statements
Date:
Aim
To write a python program to Exchange the values of two variables using simple
statements.
Algorithm :
Step1 : Start the program
Step 2 : Declare the values of x and y
Step 3 : Print before swaping x ,y
Step 4: compute x , y = y , x
Step 5 : Print after swaping x , y
Step 6 : stop the program .
Program
x=input(“Enter the value of x”)
y=input(“Enter the value of y”)
print(“Before exchange of x,y”)
print(“x=”,x)
print(“y=”,y)
x,y=y,x
print(“After exchange of x,y”)
print(“x=”,x)
print(“y=”,y)
Output
Enter the value of x 23
Enter the value of y 45
Before exchange of x,y
x=23
y=45
After exchange of x,y
x=45
y=23
Result:
Thus the above program was executed and output is verified successfully.
13
Ex. No 2.B
Circulate the Values of N Variable
Date:
Aim
To write a python program to Circulate the values of n variable using simple
statements.
Algorithm :
Step 1 : Start the program
Step 2 : Declare the value of n
Step 3 : Get the elements in the list.
Step 4 : print circulating the elements of list
Step 5 : for circulate the values of n and for i in range (n+1)
Step 6 : compute c= L[i:]+L[:i]
Step 7 : print circulation value of n
Step 8 : stop the program .
Program:
n = int(input('Enter n : '))
L=[ 91,92,93,94,95]
print("Circulating the elements of list ", L)
for i in range(n+0):
c=L[i:]+L[:i]
print(“Circulation”,i,”=”,c)
Output:
Enter n : 5
Circulating the elements of list[ 91,92,93,94,95]
Circulation 0 = [91, 92, 93, 94, 95]
Circulation 1 = [92, 93, 94, 95, 91]
Circulation 2 = [93, 94, 95, 91, 92]
Circulation 3 = [94, 95, 91, 92, 93]
Circulation 4 = [95, 91, 92, 93, 94]
Circulation 5 = [91, 92, 93, 94, 95]
Result:
Thus the above program was executed and output is verified successfully.
14
Ex. No 2.C
Distance between two points using Simple Statements
Date:
Aim:
To write a python program to find distance between two variables.
Alogrithm :
Step 1: Start the program by importing math library.
Step 2 : Declare the values of x1 , y1, x2 , y2 .
Step 3 : Calulate the distance = math.sqrt(((x2-x1)**2)+((y2-y1)**2))
Step 4 : Print the distance between two points
Step 5 : Stop the program .
Program:
import math
x1=int(input(“enter a x1 value:”))
y1=int(input(“enter a y1 value:”))
x2=int(input(“enter a x2 value:”))
y2=int(input(“enter a y2 value:”))
distance=math.sqrt(((x2-x1)**2)+((y2-1)**2))
Output:
enter a x1 value:3
enter a y1 value:2
enter a x2 value:7
enter a y2 value:8
Result:
Thus the above program was executed and output is verified successfully.
.
15
Ex. No 3.A
Programs Using Conditionals and Iterative Statements
Date: Number Series
Aim:
Program:
n = int(input('Enter a number: '))
sum=0
i=1
while(i<=n):
sum=sum+i*i
i+=1
print('Sum = ',sum)
Output:
Enter a number: 10
Sum = 385
Result:
Thus the above program was executed and output is verified successfully.
16
Ex. No 3.B
Programs Using Conditionals and Iterative Statements
Date: Number Pattern
Aim:
To write a python program to print Number Pattern.
Algorithm ;
Step 1 : Start the program .
Step 2 : Define the value of n
Step 3 : Check the condition of for i in loop (1,n+1)
Step 4: Next, check for k in range (n,i-1)
Step 5 : print (“ “)
Step 6 : Check the condition for j in range (1,1+1)
Step 7 : print (“ “)
Step 8 : Check the last condition of for m in (i-1,0-1)
Step 9 : Print (“ “)
Step 10 : print ()
Step 11: stop the program.
Program:
N = int(input("enter n value:"))
for i in range(1,N+1):
for k in range(N,i,-1):
print(" ", end =' ')
for j in range(1,i+1):
print(j, end =' ')
for m in range(i-1,0,-1):
print(m, end =' ')
print()
Output:
enter n value:5
1
121
12321
1234321
123454321
Result:
Thus the above program was executed and output is verified successfully.
17
Ex. No 3.C
Programs Using Conditionals and Iterative Statements Pyramid Pattern
Date:
Aim:
To write a python program to print Pyramid Pattern.
Algorithm :
Step 1 : Start the program .
Step 2 : Declare the value for n
Step 3 ; Check the condition for i in 1 to n+1
Step 4 : Next , check the condition for j in 0 to i
Step 5 : Print (*)
Step 6 : Print ()
Step 7 : Stop the program.
Program:
# to print pyramid pattern1
n=int(input("enter the value:"))
for i in range(1, n+1):
for j in range(0, i):
print("* ",end=' ')
print()
print(' ')
# to print pyramid pattern2
for i in range(1,n+1):
print(' '*(n-i), end=' ')
for j in range(1, i+1):
print('* ',end=' ')
print()
print(' ')
# to print pyramid pattern3
for i in range(1,n+1):
for j in range(1, n-i+2):
print('* ',end=' ')
print()
print(' ')
# to print pyramid pattern3
for i in range(1,n+1):
print(' '*(i-1), end=' ')
for j in range(1, n-i+2):
print('* ',end='')
print()
print(' ')
18
Output:
enter the value:5
*
**
***
****
*****
*
**
***
****
*****
*****
****
***
**
*
*****
****
***
**
*
Result:
Thus the above program was executed and output is verified successfully.
19
Ex. No 4.A
Operations of List
Date:
Aim:
Output:
20
first element: Books
index of 'Newspaper':2
Result:
Thus the above program was executed and output is verified successfully.
21
Ex. No 4.B
Operations of Tuple
Date:
Aim:
Program:
22
#Length of car tuple
print(' Length of Elements in Car Tuple : ',len(car))
Output:
Components of a car:('Engine', 'Battery', 'Alternator', 'Radiator', 'Steering', 'Break','Seat Belt')
first element: Engine
fourth element : Radiator
Components of a car from 0 to 4 index:('Engine', 'Battery', 'Alternator', 'Radiator','Steering')
3rd or -7th element: Engine
index of 'Alternator':2
Number of Seat belts in Car Tuple:1
Thus the above program was executed and output is verified successfully.
23
Ex. No 5.A
Operations of Set
Date:
Aim:
Step 6:Compare two set of elements using Set symmetric difference operation.
Program:
Output:
Result:
Thus the above program was executed and output is verified successfully.
24
Ex. No 5.B
Operations of Dictionaries
Date:
Aim:
Algoithm:
Program:
civ={'name':'civil structure',2:'floor',3:'stairs',4:'beams',5:'walls'}
print(civ)
print(civ['name'])
print(civ.get(4))
print(len(civ))
print('name' in civ)
print(1 in civ)
print(civ.values())
print(civ.keys())
Output:
{'name': 'civil structure', 2: 'floor', 3: 'stairs', 4: 'beams', 5: 'walls'}
civil structure
beams
5
True
False
dict_values(['civil structure', 'floor', 'stairs', 'beams', 'walls'])
dict_keys(['name', 2, 3, 4, 5])
Result:
Thus the above program was executed and output is verified successfully.
25
Ex. No 6.A
Factorial of a Number Using Recursive Function
Date:
Aim:
To write a python program to Factorial of a number using Recursive Function.
Algorithm:
Step1: Start the program.
Step2: Get the input n.
Step3: Define the function fact(x).
Step4: If x==1, then return 1.Otherwise return (x*fact(x-1)).
Step5: Print the factorial of a number.
Step6: Stop the program.
Program:
def fact(x):
if x==1:
return 1
else:
return(x*fact(x-1))
n=int(input(“Enter a number:”))
print(“The factorial of”, n,”is”,fact(n))
Output:
Enter a number:5
Result:
Thus the above program was executed and output is verified successfully.
26
Ex. No 6.B
Finding Largest Number in a List using Function
Date:
Aim:
To write a python program to find the largest number in a list using function.
Algorithm:
Step1: Start the program.
Step2: Get the input num.
Step3: Using for loop which has the range(1,num+1).Read the element in the list.
Step4: Define the function myMax (list1) and find the largest number in a list.
Step5: Print the largest number in a list.
Step6: Stop the program.
Program:
def myMax(list1):
print(“Largest element is:”, max(list1))
list1=[]
num=int(input(“Enter a number of elements in a list:”))
for i in range(1,num+1):
ele=int(input(“Enter elements:”))
list1.append(ele)
print(my Max(list1))
Output:
Enter a number of elements in a list:5
Enter elements:23
Enter elements:45
Enter elements:87
Enter elements:67
Enter elements:39
Largest element : 87
Result:
Thus the above program was executed and output is verified successfully.
27
Ex. No 6.C
Finding Area of a Shape using Function
Date:
Aim:
To write a python program to find the area of the different shapes using function.
Algorithm:
Step1: Start the program.
Step2: Define the function square.
Step3: Get the input value of side and print the area of square. (i.e., side*side)
Step4: Define the function rectangle.
Step5: Get the input value of l and b and print the area of rectangle. (i.e., l*b)
Step6: Define the function triangle.
Step7: Get the input value b and h and print the area of triangle. (i.e., 0.5*b*h)
Step8: Define the function circle.
Step9: Get the input value r and print area of circle. ((i.e., 3.14*r**2)
Step10: Print 1. square, 2. rectangle, 3. triangle and 4. circle.
Step11: Get the n value as input.
Step12: Compute if n==1, then call the function square. If no go to next step.
Step13: If n==2,then call the function rectangle. If no go to next step.
Step14: If n==3,then call the function triangle. If no go to next step.
Step15: If n==4,then call the function circle. Otherwise go to next step.
Step16: Print invalid choice.
Step17: Stop the program.
Program:
def square():
side=int(input(“Enter the side of a square:”))
print(“Area of a square:”, side*side)
def rectangle():
l=int(input(“Enter the length of a rectangle:”))
b=int(input(“Enter the breath of a rectangle:”))
print(“Area of a rectangle:”, l*b)
def triangle():
b=int(input(“Enter the base of a triangle:”))
h=int(input(“Enter the height of a triangle:”))
print(“Area of a triangle:”, b*h*0.5)
28
def circle():
r=float(input(“Enter the radius of a circle:”))
print(“Area of a circle:”, 3.14*r**2)
print(“1. Square 2. Rectangle 3. Triangle 4. Circle “)
n=int(input(“Enter your choice:”))
if n==1:square()
elif n==2:rectangle()
elif n==3:triangle()
elif n==4:circle()
else: print(“Invalid Choice”)
Output:
Area of a circle:615.44
Result:
Thus the above program was executed and output is verified successfully.
29
Ex. No 7.A
Reversing a String
Date:
Aim:
To write a python program to reverse a string.
Algorithm:
Step1: Read the input str.
Step2: Using the colon operator, the string get reversed.
Step3: Print the reversed string.
Program:
str=input(“Enter the string:”)
rev=str[::-1]
print(“The reversed string is:”,rev)
Output:
Enter the string: python
The reversed string is: nohtyp
Result:
Thus the above program was executed and output is verified successfully.
30
Ex. No 7.B
Checking Palindrome in a String
Date:
Aim:
To write a python program to check whether the given string is Palindrome.
Algorithm:
Program:
rev=str[::-1]
if str==rev:
else:
Output:
Result:
Thus the above program was executed and output is verified successfully.
31
Ex. No 7.C
Counting Characters in a String
Date:
Aim:
To write a python program to count a character in a string.
Algorithm:
Step1: Get the input str and ch.
Step2: Using the count method find the number of characters in str and assign it as val.
Step3: Print val
Step4: stop the program.
Program:
str=input(“Enter the string”)
ch=input(“Enter the character:”)
val=str.count(ch)
print(val)
Output:
Enter the string: PYTHON PROGRAMMING
Enter the character: G
2
Result:
Thus the above program was executed and output is verified successfully.
32
Ex. No 7.C
Replace Characters in a String
Date:
Aim:
To write a python program to replace a character in a string.
Algorithm:
Step1: Start the program.
Program:
str=input(“Enter the string:”)
print(str.replace(old,new))
Output:
Enter the string: PYTHON PROGRAMMING
C PROGRAMMING PROGRAMMING
Result:
Thus the above program was executed and output is verified successfully.
33
Ex. No 8.A
Compare the Elements of the Two Pandas Series using Pandas Library
Date:
Aim:
To write a python program to compare the elements of the two Pandas series using pandas
library.
Algorithm:
Step1: Start the program.
Step2: Import the library function Pandas.
Step3: Give the inputs as ds1, ds2 in the form of lists.
Step4:ds1 is interpreted as Series1.
Step5:ds2 is interpreted as Series2.
Step6: Compare Series1 and Series2 and follow the steps 6.1,6.2,6.3.
6.1.ds1==ds2
6.2.ds1>ds2
6.3.ds1<ds2
Program:
import pandas as pd
ds1 = pd.Series([2, 4, 6, 8, 10])
ds2 = pd.Series([1, 3, 5, 7, 10])
print("Series1:")
print(ds1)
print("Series2:")
print(ds2)
print("Compare the elements of the said Series:") print("Equals:")
print(ds1 == ds2)
print("Greater than:")
print(ds1 > ds2)
print("Less than:")
print(ds1 < ds2)
Output:
Series1:
02
14
26
38
4 10
dtype: int64
34
Series2:
01
13
25
37
4 10
dtype: int64
Compare the elements of the said Series:
Equals:
0 False
1 False
2 False
3 False
4 True
dtype: bool
Greater than:
0 True
1 True
2 True
3 True
4 False
dtype: bool
Less than:
0 False
1 False
2 False
3 False
4 False
dtype: bool
Result:
35
Ex. No 8.B
To Test whether None of the Elements of a Given Array is Zero Using Numpy
Library
Date:
Aim:
To write a python program to test whether none of the elements of a given array is
zero using numpy library.
Algorithm:
Step1:Start the program.
Step2:Import the numpy library as np.
Step3:Give the input x as array.
Step4:Print x as Original Array.
Step5:Check whether any of the elements is zero or not.
Step6:print the statement.
Step7:Close the program.
Program:
import numpy as np
x = np.array([1, 2, 3, 4])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print(np.all(x))
x = np.array([0, 1, 2, 3])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print(np.all(x))
Output:
Original array:
[1 2 3 4]
Test if none of the elements of the said array is zero:
True
Original array:
[0 1 2 3]
Test if none of the elements of the said array is zero:
False
Result:
Thus, the given program successfully executed and practically verified.
36
Ex. No 8.C
To Plot a Graph Using Matplotlib Library
Date:
Aim:
To write a python program to plot a graph using matplotlib library.
Algorithm:
Step1:Start the program.
Step2:Import matplotlib and numpy as plt and np respectively.
Step3:Give input xpoints and ypoints in the form of array.
Step4:Now plot the points using plt.plot function.
Step5:Display the graph using plt.show() fuction
Step6:Close the program.
Program:
Output:
Result:
Thus, the given program successfully executed and practically verified.
37
Ex. No 8.D
To Return the Specified Unit in Seconds Using Scipy Library
Date:
Aim:
To write a python program to return the specified unit in seconds (e.g. hour returns 3600.0)
using scipy library.
Algorithm:
Step1: Start the program.
Program:
from scipy import constants
print(constants.minute)
print(constants.hour)
print(constants.day)
print(constants.week)
print(constants.year)
print(constants.Julian_year)
Output:
60.0
3600.0
86400.0
604800.0
31536000.0
31557600.0
Result:
Thus, the given program successfully executed and practically verified.
38
Ex. No 9.A
COPY FROM ONE FILE TO ANOTHER FILE
Date:
Aim:
To write a python program to copy from one file to another file.
Algorithm:
Step-1- Start the program
Step-2- Import the copy file from the shutil
Step-3- Enter the source file
Step-4- Enter the destination file
Step-5- The file copy from the source file to the destination file using copy file module.
Step-6- If the file is successfully copied, then show „file copied successfully‟
Step-7- Open the destination file and read.
Step-8- Close the file.
Step-9- Stop the program.
Program:
from shutil import copyfile
sourcefile = input("Enter source file name: ")
destinationfile = input("Enter destination file name: ")
copyfile(sourcefile, destinationfile)
print("File copied successfully!")
c = open(destinationfile, "r")
print(c.read())
c.close()
print()
print()
Output:
Enter source file name: file1.txt
Enter destination file name: file2.txt
File copied successfully!
Sunflower
Jasmine
Roses
Result:
Thus, the given program successfully executed and practically verified.
39
Ex. No 9.B
WORD COUNT FROM FILE
Date:
Aim:
To write a python program to count number of word in a file.
Algorithm:
Step-1: Start the program.
Step-2: Open the file by using open module and read the file as the text format denoted by „rt‟.
Program:
Output:
Number of words in text file : 36
Result:
Thus, the given program successfully executed and practically verified.
40
Ex. No 9.C
Finding Longest Word in a File
Date:
Aim:
To write a python program to find the longest word in a file.
Algorithm:
Step-1- Start the program.
Sub function()
Step-2- open the file and read and split the words.
Program:
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('F:\Data.txt'))
Output:
['collection']
Result:
Thus, the given program successfully executed and practically verified.
41
Ex. No 10.A
Divide by Zero Error using Exception Handling
Date:
Aim:
To write a python program to handle divide y zero error using exception handling.
Algorithm:
Step-1- Start the Program
Step-2- Get num1, num2.
Step-3- Evaluate the result by num1/num2.
Step-4- print result.
Step-5- Otherwise display the e.
Step-6-End the program.
Program:
try:
num1=int(input("enter first number:"))
num2=int(input("enter second number:"))
result=num1/num2
print(result)
except ValueError as e:
print("invalid input please input integer..")
except ZeroDivisionError as e:
print(e)
Output:
enter first number: 33
enter second number:23
1.434782608695652
Result:
Thus, the given program successfully executed and practically verified.
42
Ex. No 10.B
Voters Age Validity Using Exception Handling
Date:
Aim:
To write a python program to check voters age validity.
Algorithm:
Step-1- Start the program by defining main function.
Step-2- Get the age as input.
Step-3- Check the condition age>18, display eligible to vote, otherwise, display not eligible.
Step-4- if the try block is not executed, exception block get executed.
Step-5- Stop the program.
Program:
def main():
try:
age=int(input("enter your age"))
if age>18:
print("eligible to vote")
else:
print("not eligible to vote")
except ValueError as err:
print(err)
print("an error occured")
print("rest of the code...")
main()
Output:
enter your age18
not eligible to vote
Result:
Thus, the given program successfully executed and practically verified.
43
Ex. No 10.C
Student Mark Range Validation
Date:
Aim:
To write a python program to perform student mark range validation.
Algorithm:
Step-1- Start the Program by defining main function.
Step-2- Get marks Step-3- using try Check if mark>=3 and mark<101 display pass and mark is
valid, otherwise fail.
Step-4- Otherwise display the exception block.
Step-5- Stop the Program.
Program:
def main():
try:
mark=int(input("Enter your mark:"))
if mark>=35 and mark<101:
print("pass and your mark is valid")
else:
print("fail and your mark is valid")
except ValueError:
print("mark must be a valid number")
except IOError:
print("Enter correct valid mark")
except:
print("An ERror occured")
main()
Output:
Enter your mark:59
pass and your mark is valid
Result:
Thus, the given program successfully executed and practically verified.
44
Ex. No 11
Exploring Pygame
Date:
PYGAME INSTALLATION
To Install Pygame ModuleSteps
1. Install python 3.6.2 into C:\
2. Go to this link to install pygame www.pygame.org/download.shtml
3. Click
pygame-1.9.3.tar.gz ~ 2M and download zar file
4. Extract the zar file into C:\Python36-32\Scripts folder
5. Open command prompt
Type the following command
C:\>py -m pip install pygame --
userCollecting pygame
Downloading pygame-1.9.3-cp36-cp36m-win32.whl (4.0MB)
45
8. To see if it works, run one of the included examples in pygame-1.9.3
C:\>cd Python36-32\Scripts\pygame-1.9.3
C:\Python36-32\Scripts\pygame-1.9.3>cd
examples
C:\Python36-32\Scripts\pygame-
1.9.3\examples>aliens.pyC:\Python36-
32\Scripts\pygame-1.9.3\examples>
46
Ex. No 12
Simulate Bouncing Ball using Pygame
Date:
Aim:
To write a python program to bouncing ball in pygame.
Algorithm:
Step1: Start the program.
Step2: Set screen size and background color.
Step3: Set speed of moving ball.
Step4: Create a graphical window using set_ mode()
Step5: Set caption.
Step6: Load the ball image and create a rectangle area covering the image
Step7: Use blit() method to copy the pixel color of the ball to the screen
Step8: Set back ground color of screen and use flip() method to make all
images visible.
Step9: Move the ball in specified speed.
Step10: If ball hits the edges of the screen reverse the direction.
Step11: Create an infinite loop and Repeat steps 9 and 10 until user qu its the
progra m
Step12: Stop the program
Program:
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:
47
speed[1] = -speed[1]
screen.fill(background)
screen.blit(ball, ballrect)
pygame.display.flip()
ball.jpg
Output:
Result:
Thus, the given program successfully executed and practically verified.
48