GE3171_PSPP_Lab Record
GE3171_PSPP_Lab Record
COIMBATORE-107
Department of
Place:
Date:
MA FACUL
EX.NO EXPERIMEN PAG
TS R TY
E NO
KS SIGN
1 Flowcharts for simple real life or scientific or technical problems
1 Electricity Billing 1
a
1 Retail Shop Billing 3
b
1 Result of SINE Series 5
c
1 Weight of Motorbike 7
d
1 Weight of Steel Bar 8
e
1 Compute Electrical Current in Three Phase AC Circuit 9
f
2 Python programming using simple statements and expressions
2 Exchange the values of two variables 10
a
2 Circulate the values of n variables 11
b
2 Distance between two points 12
c
3 Scientific problems using Conditionals and Iterative loops
3 Number Series 13
a
3 Number Pattern 13
b
3 Pyramid Pattern 14
c
Implementing real-time/technical applications using Lists, Tuples.
4 (Items present in a library/Components of a car/ Materials required
for construction of a building –operations of list & tuples)
Basic list operations in items present in a
4 library/Components of a car/ Materials required 15
a for construction of a building
Basic tuple operations in items present in a 17
4 library/Components of a car/ Materials required
b for construction of a building
Implementing real-time/technical applications using Sets,
5 Dictionaries. (Language, components of an automobile, Elements
of a civil structure, etc.- operations of Sets & Dictionaries)
5 Basic Set Operations 18
a
5 Basic Dictionary Operations 19
b
Implementing programs using Functions. (Factorial, largest
6
number in a list, area of shape)
6 Calculate Factorial Using Functions 20
a
6 Finding largest number in a list using Functions 21
b
6 Calculate area of shape using Functions 22
c
Implementing programs using Strings. (Reverse, palindrome, character
7
count, replacing characters)
7a Reverse the string 23
7b Palindrome of a string 24
7c Count the character of string 25
7d Replacing the existing character in a string 26
Implementing programs using written modules and Python Standard
8
Libraries (pandas, numpy, Matplotlib, scipy)
8a Python programs using pandas module. 27
8b Python programs using numpy module. 29
.i.
8b Matrix Operations using numpy module 30
.ii
8c Python programs using Matplotlib module 31
8d Python programs using scipy module 32
Implementing real-time/technical applications using file handling.
9
(copy from one file to another, word count, longest word)
9a Copy from one file to another 33
9b Count number of words in a string 34
9c Find the longest word in a file 35
Implementing real-time/technical applications using Exception
10
handling. (divide by zero error, voter’s age validity, student mark
range validation)
10 Handling exception divide by zero error 36
a
10 Handling exception voters age validity 37
b
10 Handling exception Student mark range validation 38
c
11 Exploring Pygame tool.
11 Getting Started with PyGame 39
a
11 Image loading using Pygame 40
b
11 Font Style and size in Pygame 41
c
12 Developing a game activity using Pygame like bouncing ball, car race etc.
12 Bouncing Ball using Pygame 42
a
12 Simulate Car Race using Pygame 44
b
12 Simulate Elliptical Orbits in Pygame 49
c
Total
Average
Ex. No: 1 Date:
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 a
motorbike, Weight of a steel bar, compute Electrical Current in Three Phase ACCircuit, etc.)
Aim:
To Identification and solving of simple real life or scientific or technical problems, and
developing flow charts for the same.
1a. Electricity Billing
To input electricity unit charges and calculate total electricity bill
Algorithm
Step 1: Start
Step 2: Read unit
Step 3: If unit< = 100 then Electricity_Charge = 0
Step 4: else if unit <= 200 goto step 5 otherwise goto step 6
Step 5: Calculate Chargeable_unit and Electricity_Charge using the
formula Electricity_Charge = (100 * 0) + (units - 100)*1.5+20
Step 6: If unit <= 500 goto step 7 otherwise goto step 8
Step 7: Calculate Chargeable_unit and Electricity_Charge using the formula
Electricity_Charge = (100 * 0) + (100*2) + (units-200) * 3 + 30
Step 8: Calculate Chargeable_unit and Electricity_Charge using the formula Electricity_Charge
= (100 * 0) + (100 * 3.5) + ( 300 *4.6)+(units- 500)*6.6 + 50
Step 9: Print the value of
Electricity_Charge Step 10: Stop
Flowchart
Pseudo code
BEGIN
READ units
IF unit< = 100 THEN Electricity_Charge =
0 ELSE
IF unit <= 200 THEN
Electricity_Charge = (100 * 0) + (units - 100)*1.5+20
ELSE IF unit <= 500 THEN
Electricity_Charge = (100 * 0) + (100*2) + (units-200) * 3 + 30ELSE
Electricity_Charge = (100 * 0) + (100 * 3.5) + ( 300 *4.6)+(units- 500)*6.6 + 50END
IF
END
IF END
IF
PRINT Electricity_Charge
END
1b. Retail
Shop Billing
Algorithm
Step 1: Start
Step 2: Initialize the system and
total Step 3: Read the Barcode
Step 4: If barcode matched means read data from memory and display the value
Step 5: Add the total amount as items is added
Step 6: If any items removed then reduce the item value from the total
amount Step 7: Display the total amount
Step 8: Print the
bill Step 9: Stop
Pseudo code
BEGIN
Total=0
FOR all items in list
READ barcode
DISPLAY value
Total = total
+value
END FOR
IF item removed
Total = Total –Item_value
END IF
PRINT Total
END
Flowchart
1c. The Flowchart for calculating the result of Sine series
Description
sin (x) = (x^1/1!) - (x^3/3!) + (x^5/5!) - (X^7/7!) + ...n
input x is degrees. So we need to convert degree to radian. Formula for converting degree to radianis
x*(3.14159/180)
Algorithm
Step 1: Start
Step 2: Read n, x
Step 3: fact =1, sum=x, i=3, sign=-
1 Step 4: Calculate x=x/180*3.14
Step 5: If i<=n then goto step 6 else goto step
11 Step 6: Calculate fact = fact *i *(i-1)
Step 7: sum= sum
+pow(x,i)/fact Step 8: sign = sign * -
1
Step 9: i=i+2
Step 10: goto step
5 Step 11: Print sum
Step 12: Stop
Pseudo code
BEGIN
READ
n,x
INITIALIZE fact=1, sum=x, i=3, sign=-
1 CALCULATE x=x/180*3.14
FOR (if i<=n)
CALCULATE fact = fact *i *(i-1)
CALCULATE sum= sum
+pow(x,i)/factCALCULATE sign =
sign * -1 CALCULATE i=i+2
END FOR
PRINT
sum END
Flowchart
No
1d. Weight of a
Motorbike Description
The formula used to calculate weight of motorbike is w = mg
Where w=weight in Newton’s or kilograms-force, m=mass in
kilograms, g=9.81 Algorithm
Step 1: Start
Step 2: Read the value m
Step 3: Initialize g =9.81
Step 4: Calculate w = mg
Step 5: Print W
Step 6: Stop
Flowchart
Pseudo
code
BEGIN
READ m
INITIALIZE g=9.81
CALCULATE W= m* g
PRINT W
END
1e. WEIGHT OF A STEEL BAR
Description
The formula used to calculate the unit weight of steel bars is D²L/162. Where, D = Dia. Of
steelbars, 162 is a constant value.
Steel Weight formula W =
D2L/162W- Weight of steel bar
D – Diameter of steel bars in MML
– Length of bars in meter
Algorithm
Step 1: Start
Step 2: Read the values D, L
Step 3: Calculate W= (D
*D*L)/162 Step 4: Print W
Step 5: Stop
Flowchart
Pseudo
code
BEGIN
READ D, L
CALCULATE W=
(D*D*L)/162 PRINT W
END
1f. COMPUTE ELECTRICAL CURRENT IN THREE PHASE AC CIRCUIT
Description
I = P / (3 × pf × V)
Where P is the power, pf is the power factor, V is the voltage and, I is the current
Algorithm
Step 1: Start
Step 2: Read the values P, pf and V
Step 3: Calculate
I=P/(sqrt(3)*pf*V) Step 4: Print I
Step 5: Stop
Flowchart
Pseudo code
BEGIN
READ P, pf, V
CALCULATE I= P / (sqrt(3)*pf
*V) PRINT I
END
Result:
To Identification and solving of simple real life or scientific or technical problems, and
developing flow charts are demonstrated successfully.
Ex. No: 2 Date:
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 to exchange the values of two variables.
Algorithm
step 1:Declared a temporary variable a and b
step 2:Assign the value of a and b,
step 3:Assign the value of a to b, and b to a
step 4: we don’t even need to perform arithmetic operations. We can use:
a,b = b,a
step 5:to print the result
Program
USING TUPLE
x=5
y=10
x,y=y,x
print('x=',x)
print('y=',y)
x=5
y=10
TEMP = x
x=y
y = TEMP
print('x=',x)
print('y=',y)
OUTPUT:
1. x= 10
y= 5
2. x= 10
y= 5
2b. Circulate the values of n variables
Aim
To write a python program to circulate the values of n variables.
Algorithm
Program:
OUTPUT:
Aim
To write a python program to calculate distance between two points.
Algorithm
Step 1: Start the program
Step 2: Read the
x, y coordinate
values fro point
1 and point 2
Step 3: Calculate
the distance
using the
formula sqrt(dx2
+dy2) Step 4:
Print the distance
Step 5: Stop the program
Program
OUTPUT
Enter x1=.8
Enter y1=8.9
Enter x2=7.9
Enter y2=0.7
Distance = 10.846658
Result
Thus the above Python programming using simple statements and expressions has been
executed and verified output successfully.
Ex. No: 3 Date:
Scientific problems using Conditionals and Iterative loops. (Number Series, Number
Patterns, Pyramid Pattern)
3a. Number Series
Aim
To write a python program to display number series using conditionals and iterative loops.
Algorithm
Program
n=5
pypart(n)
Output
1
11
111
1111
11111
3b. Number Patterns
To write a python program to display number patterns using conditionals and iterative loops.
Algorithm
Step 1: Start the program
Step 2: Declare the value for rows.
Step 3: Let i and j be an integer number
Step 4: Repeat step 5 to 8 until all value parsed
Step 5: Set i in outer loop using range function, i = rows+1 and rows will be initialized to
Step 6: Set j in inner loop using range function and i integer will be initialized to j
Step 7: Print i until the condition becomes false in inner loop.
Step 8: Print new line until the condition becomes false in outer loop.
Step 9: Stop the program.
Program
for i in range(rows):
for j in range(i+1):
print (j+1 , end=" ")
print("\n")
Output
12
123
1234
12345
3c.Pyramid Pattern
Aim
To write a python program to display pyramid patterns using conditionals and iterative loops.
Algorithm
Step 1: Start the program
Step 2: Read number of
rows
Step 3: Using range function and inner loops to find the values
Step 4: Using while loop to print the pattern values
Step 4: Stop the program
Program
k=0
while k!=((2*i)-1):
print("* ", end="")
k += 1
k=0
print()
Output
*
***
*****
*******
*********
Result
Thus the above Python program for various scientific problems like Number Series, Number Patterns, and
Pyramid Pattern executed and verified successfully.
Ex. No: 4 Date:
Implementing real-time/technical applications using Lists, Tuples. (Items present in a
library/Components of a car/ Materials required for construction of a building –operationsof list &
tuples)
Aim
To create a python program to perform for basic list operations in items present in a
library/Components of a car/ Materials required for construction of a building
Algorithm
Program
library=["books","author","barcodenumber","price"]
library[0]="ramayanam"
print(library[0])
library[1]="valmiki"
library[2]=123987
library[3]=234
print(library)
tup1=(12134,250000)
tup2=('books','totalprice')
tup3=tup1+tup2;
print(tup3)
Output
ramayanam
['ramayanam', 'valmiki', 123987, 234]
(12134, 250000, 'books', 'totalprice')
4b) Basic tuple operations in items present in a library/Components of a car/ Materials
required for construction of a building
Aim
To create a python program to perform for basic tuple operations in items present in a
library/Components of a car/ Materials required for construction of a building
Algorithm
Program
for i in cars:
if "M" in i:
new_list.append(i)
print(new_list)
Output
Result
Thus the above Python program for real time/technical applications using lists and tuples are executed and
verified successfully.
Ex. No: 5 Date:
Implementing real-time/technical applications using Sets, Dictionaries. (Language,
components of an automobile, Elements of a civil structure, etc.- operations of Sets &
Dictionaries)
5a) Basic Set
Operations Aim
To create a python program to perform basic sets operations for Language, components ofan
automobile, Elements of a civil structure.
Algorithm
Step 1: Start the program
Step 2: Define sets for language, automobile, civilelements with elements
Step 3: Perform various set operations
Step 4: Stop the program
Program
Output
Dict = {}
print("Empty Dictionary: ")
print(Dict)Dict[0] = 'BRICKS'
Dict[2] = 'CEMENT'
Dict[3] = 'BLUE PRINT'
print("\nDictionary after adding 3 elements: ")
print(Dict)
Dict['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ")
print(Dict)
Dict[2] = 'STEEL'
print("\nUpdated key value: ")
print(Dict)
Dict[5] = {'Nested': {'1': 'LIME', '2': 'SAND'}}
print("\nAdding a Nested Key: ")
print(Dict)
Output
Empty Dictionary:
{}
Aim
To create a python program to calculate factorial value using functions.
Algorithm
Program
def
factorial(n):
return 1
else:
return(n*factorial(n-1))
n = int(input("Enter
number:")) print("Factorial:",
factorial(n))
Output
Enter number:5
Factorial: 120
6b) Finding largest number in a list using
Functions Aim
To create a python program to finding largest number in a list of numbers using functions.
Algorithm
Program
Output
2
6c) Calculate area of shape using Functions
Aim
To create a python program to calculate area of shape using Functions
Algorithm
Step 1: Start the program
Step 2: Read the name of the shape
Step 3: Pass the shape as an argument to a calculate_area function.
Step 4: Using the method lower convert the shape name as
lowercase.
Step 5: Check the matching shape name and calculate the area of specific
shape. Step 6: Print the value of area.
Step 7: Stop the program
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":
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("The area of circle 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)
Result
Thus the above Python program using functions are executed and verified successfully.
Ex. No: 7 Date:
Program
def reverse(string):
string="".join[reversed(string))
return string
s=input("Enter ang string:")
print("The oringinal string is:",end"")
print(s)
print("The reversed string(using reversed/is:",end="")
print(reverse(s))
Output
string
Aim
To create a python program to check whether the given string is palindrome or not.
Algorithm
Program
str=input(“enter string”)
str=str. Casefold()
rev.str=reversed(str)
if list (str)=list(rev_str):
print(“ It’s a palindrome”)
else:
print(“ It’s not a palindrome”)
Output
Aim
To create a python program to count the character of string.
Algorithm
Program
Output
Aim
Algorithm
Step 1: Start the
program Step 2: Read
string
Step 3: Read the replacement
character Step 4: Read the new
character
Step 5: Using the method replace to change the
character. Step 6: Print the updated string
Step 7: Stop the Program
Program
str=input(“Enter a string”)
old str = input(“Enter the old character to be replace:”)
restr=input(“Entrerbthe character”)
result=str. replace(old str,restr)
print(result)
Output
Result
Thus the python program to perform basic string operations are executed and verified successfully.
Python program to perform basic string operations are executed and verified successfully.
Ex. No: 8 Date:
Implementing programs using written modules and Python Standard Libraries (pandas,numpy,matplotlib,scipy)
Aim
Pandas is an open source Python package that provides numerous tools for data analysis. The package
comes with several data structures that can be used for many different data manipulation tasks.
Algorithm
Program
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
Aim
To create a python program for basic operations using numpy.
Description
NumPy is a Python library used for working with arrays. NumPy stands for NumericalPython.
NumPy provide an array object that is up to 50x faster than traditional Python lists.
Algorithm
Program
import numpy as np
arr = np.array([[1, 5, 6],
[4, 7, 2],
[3, 1, 9]])
# maximum element of array
print ("Largest element is:", arr.max())
print ("Row-wise maximum elements:", arr.max(axis =
1))# minimum element of array
print ("Column-wise minimum elements:", arr.min(axis = 0))
Aim
To create a python program for basic matrix operations using numpy module.
Algorithm
Step 1: Start the program
Step 2: Initialize the two different matrixs
Step 3: Using numpy module calculate the basic matrix operations and print the results
Step 4: Stop the program
Program
import numpy
# Two matrices are initialized by valuex
= numpy.array([[1, 2], [4, 5]])
y = numpy.array([[7, 8], [9, 10]])
print("X:",x)
print("Y:",y)
# add()is used to add matrices print
("Addition of two matrices: ")print
(numpy.add(x,y))
# subtract()is used to subtract matrices
print ("Subtraction of two matrices : ")
print (numpy.subtract(x,y))
# divide()is used to divide
matrices print ("Matrix Division :
")
print (numpy.divide(x,y))
print ("Multiplication of two matrices:
") print (numpy.multiply(x,y))
print ("The product of two matrices :
") print (numpy.dot(x,y))
print ("square root is :
") print (numpy.sqrt(x))
print ("The summation of elements :
") print (numpy.sum(y))
print ("The column wise summation : ")
print (numpy.sum(y,axis=0))
print ("The row wise summation:
") print (numpy.sum(y,axis=1))
# using "T" to transpose the matrix
print ("Matrix transposition : ")
print (x.T)
8c). Implementing Python programs using Matplotlib module
Aim
To create a python program to plotting graphs using matplotlib module.
Description
Matplotlib.pyplot is a plotting library used for 2D graphics in python programming language. It
can be used in python scripts, shell, web application servers and other graphical user interface toolkits.
Matploitlib is a Python Library used for plotting, this python library provides and objected-oriented APIs
for integrating plots into applications.
Algorithm
Step 1: Start the program
Step 2: Import the matplotlib module
Step 3: Define x axis and y axis values in list x and y
Step 4: Using plt.title, plt.xlabel and plt.ylabel method to display the title of the graph, naming thex axis
and y axis.
Step 5: Use the method plt.plot() method to plot the points, plt.bar() to bar graph
Step 6: Display the graph using the methos plt.show()
Step 7: Stop the program
Program
import matplotlib.pyplot as
plt from matplotlib import
style style.use('ggplot')
x = ["PSPP", "Chemistry", "English", "Maths", "Physics"]y
= [85,70,68,80,75]
plt.title('Student Mark
Analysis') plt.xlabel('Subject
Name') plt.ylabel('Marks')
plt.plot(x, y)
plt.yticks(list(range(0,100,10)))plt.show(
) plt.title('Student Mark Analysis')
plt.xlabel('Subject Name')
plt.ylabel('Marks')
plt.bar(x,y)
plt.show()
8d). Implementing Python programs using scipy module
Aim
To create a python program to perform various operation using scipy module.
Description
SciPy in Python is an open-source library used for solving mathematical, scientific, engineering,
and technical problems. It allows users to manipulate the data and visualize the data using a wide range of
high-level Python commands.
Algorithm
Step 1: Start the program
Step 2: Import necessary modules
Step 3: Perform simple mathematical operations using scipy module and print the results.
Step 4: Stop the program
Program
import numpy as np
from scipy import constants, ndimage,
miscfrom scipy.special import cbrt
from matplotlib import pyplot as plt
print(constants.pi)
print(constants.kilo)
print(constants.deci)
print(constants.minute)
print(constants.hour)
from scipy.sparse import csr_matrix arr =
np.array([0, 0, 0, 0, 0, 1, 1, 0, 2])
print(csr_matrix(arr))
#Find cubic root
a=int(input("Enter the value:
"))cb
= cbrt(a)
print("Cubic root of",a,"is",cb)
#get face image of panda from misc
package panda = misc.face()
#plot or show image of
face plt.imshow( panda )
plt.show()
#rotatation function of scipy for image – image rotated 135 degree
panda_rotate = ndimage.rotate(panda, 135)
plt.imshow(panda_rotate) plt.show()
Result
Thus the above Python program using modules and standard libraries are executed and verified successfully.
Ex. No: 9 Date:
Implementing real-time/technical applications using file handling. (copy from one file to another,
word count, longest word)
9a) Implementing Python programs for copy from one file to another
Aim
To create a python program for copy the content from one file to another file.
Algorithm
Program
outfile.write(line)
print("File
Copied...")
Output:
string Aim
Algorithm
Program
output:
Enter the file name with extension:hello world
Number of words in text file :11
9c) Implementing Python programs for find the longest word in a file
Aim
To create a python program for find the longest word in a file.
Algorithm
Step 1: Start the program
Step 2: Read the file name
Step 3: Pass the filename as argument of function
longest_word Step 4: Open the file in read mode
Step 5: Using the method split(), len() and max() to find and return the longest word
Step 6: Print the longest word.
Step 7: Stop the program
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]
OUTPUT
Enter the file name : photos
Longest word in this file is : artificial
Result
Thus the above Python program using file handling operations are executed and verified successfully.
Ex. No: 10 Date:
Implementing real-time/technical applications using Exception handling. (divide by zero
error, voter’s age validity, student mark range validation)
10a) Implementing Python programs for handling exception divide by zero error
Aim
To create a python program for handling exception divide by zero error
Algorithm
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
Aim
To write a python program for handling exception on voters age validity.
Algorithm
Program
while True:
try:
age=int(input("Please enter your age"))
except ValueError:
print("Sorry, I didnt understand that")
continue
if(age<0):
print("Sorry, your reponse must not be negtaive")
continue
else:
break
if(age>=18):
print("You are eligible to vote")
else:
print("You are not eligible to vote")
Output
Step 4: If no exception then check the range and print the Grade
Step 5: Stop the program
Program
while True:
studentmark=int(input("Enter the student marks"))
if(studentmark<0 or studentmark>100):
print("The student mark value is out of range, try again")
else:
print("The student mark entered is valid")
break
Output
Result
Thus the above Python program using exception handling are executed and verified successfully.
Ex.No : 11 Date:
Aim
To create a python program for getting started with pygame.
Algorithm
Step 1: Start the program
Step 2: Import the pygame module
Step 3: Initialize Pygame using pygame.init () method.
Step 4: Set the name for the window using the method pygame.display.set_caption()
#importing
libraries import
pygame
# initializing the
pygame pygame.init()
#Setting name of the window
pygame.display.set_caption ("pygame
window")
# drawing the surface
surface=
pygame.display.set_mode((400,300)) done =
False
#initializing the
color color =
(255,0,0)
#Loop to control our window
while not done:
for event in pygame.event.get():
if event.type ==
pygame.QUIT: done =
True
pygame.display.flip()
# drawing the circle
pygame.draw.circle(surface, color, (150,150), 30)
pygame.display.flip()
OUTPUT:
11. b. Image loading using Pygame
Aim
To create a python program for image loading using pygame.
Algorithm
Step 1: Start the program
Step 2: Import the pygame module
Step 3: Initialize Pygame using pygame.init () method.
Step 4: Create the game window using the method pygame.display.set_mode ()
Step 5: Control the window using loop
Step 6: Load the necessary images using the method pygame.image.load()
Step 7: Quit the pygame using the method pygame.quit()
Step 8: Stop the program
Program
import
pygame
pygame.init()
pygame.display.set_caption ("pygame window")
surface= pygame.display.set_mode((500,600)) done
= False
clock =
pygame.time.Clock() while
not done:
for event in pygame.event.get():
if event.type ==
pygame.QUIT: done =
True
surface.fill((255, 255, 255))
image =
pygame.image.load(r"rose.jpg")
surface.blit(image,(0, 0))
pygame.display.flip()
clock.tick(60
) pygame.quit()
OUTPUT:
11 c. Font Style and size in
Pygame Aim
To create a python program for changing font and style using pygame.
Algorithm
Step 1: Start the program
Step 2: Import the pygame module
Step 3: Initialize Pygame using pygame.init() method.
Step 4: Create the game window using the method pygame.display.set_mode ()
import
pygame
pygame.init()
window =
pygame.display.set_mode((800,500)) clock =
pygame.time.Clock()
done = False
font = pygame.font.SysFont(None,50)
text = font.render("Python Programming Lab", True, (255, 0,
0))while not done:
for event in pygame.event.get(): if
event.type == pygame.QUIT:
done = True
window.fill((255, 255, 255))
window.blit(text,
[text.get_width()//2,text.get_height()//2])
pygame.display.flip()
clock.tick(60
) pygame.quit()
OUTPUT:
Result
Thus the above Python program using exception handling are executed and verified successfully.
Ex. No: 12 Date:
Developing a game activity using Pygame like bouncing ball, car race etc.
Algorithm
Program
import pygame
pygame.init() window_w
= 800
window_h = 600
white = (255, 255, 255)
green = (0,255, 0)
FPS = 120
window = pygame.display.set_mode((window_w,
window_h)) pygame.display.set_caption("Bouncing Ball ")
clock =
pygame.time.Clock() def
game_loop():
block_size = 20
velocity = [1, 1] pos_x
= window_w/2
pos_y = window_h/2
running = True while
running:
for event in
pygame.event.get():if
event.type == pygame.QUIT:
pygame.quit(
) quit()
pos_x +=
velocity[0] pos_y
+= velocity[1]
if pos_x + block_size > window_w or pos_x < 0:
velocity[0] = -velocity[0]
if pos_y + block_size > window_h or pos_y <
0: velocity[1] = -velocity[1]
# DRAW
window.fill(white)
pygame.draw.circle(window,green, (pos_x, pos_y),
block_size) pygame.display.update()
clock.tick(FPS)
game_loop()
OUTPUT :
12 b. Simulate Car Race
Algorithm
Program
import random
from time import
sleep import pygame
# enemy_car
self.enemy_car = pygame.image.load('.\\img\\enemy_car_1.png')
self.enemy_car_startx = random.randrange(310, 450)
self.enemy_car_starty = -600
self.enemy_car_speed = 5
self.enemy_car_width = 49
self.enemy_car_height = 100
# Background
self.bgImg = pygame.image.load(".\\img\\back_ground.jpg")
self.bg_x1 = (self.display_width / 2) - (360 / 2)
self.bg_x2 = (self.display_width / 2) - (360 / 2)
self.bg_y1 = 0
self.bg_y2 = -600
self.bg_speed = 3
self.count = 0
def racing_window(self):
self.gameDisplay = pygame.display.set_mode((self.display_width, self.display_height))
pygame.display.set_caption('Car Dodge')
self.run_car()
def
run_car(self):
while not self.crashed:
for event in pygame.event.get(): if
event.type == pygame.QUIT:
self.crashed = True#
print(event)
if (event.type ==
pygame.KEYDOWN):if (event.key
== pygame.K_LEFT):
self.car_x_coordinate -= 50
print ("CAR X COORDINATES: %s" %
self.car_x_coordinate)if (event.key == pygame.K_RIGHT):
self.car_x_coordinate += 50
print ("CAR X COORDINATES: %s" % self.car_x_coordinate)
print ("x: {x}, y: {y}".format(x=self.car_x_coordinate, y=self.car_y_coordinate))
self.gameDisplay.fill(self.black
) self.back_ground_raod()
self.run_enemy_car(self.enemy_car_startx,
self.enemy_car_starty) self.enemy_car_starty +=
self.enemy_car_speed
self.car(self.car_x_coordinate,
self.car_y_coordinate) self.highscore(self.count)
self.count += 1
if (self.count % 100 == 0):
self.enemy_car_speed += 1
self.bg_speed += 1
if self.car_y_coordinate < self.enemy_car_starty + self.enemy_car_height:
if self.car_x_coordinate > self.enemy_car_startx and self.car_x_coordinate <
self.enemy_car_startx + self.enemy_car_width or self.car_x_coordinate + self.car_width >
self.enemy_car_startx and self.car_x_coordinate + self.car_width < self.enemy_car_startx +
self.enemy_car_width:
self.crashed = True
self.display_message("Game
Over !!!")
pygame.display.update()self.clock.tick(60
def back_ground_raod(self):
self.gameDisplay.blit(self.bgImg, (self.bg_x1,
self.bg_y1))self.gameDisplay.blit(self.bgImg, (self.bg_x2,
self.bg_y2))
self.bg_y1 +=
self.bg_speed self.bg_y2
+= self.bg_speed
if self.bg_y1 >=
self.display_height: self.bg_y1 =
-600
if self.bg_y2 >=
self.display_height: self.bg_y2 =
-600
def run_enemy_car(self, thingx, thingy):
self.gameDisplay.blit(self.enemy_car, (thingx,
thingy))
def display_credit(self):
font = pygame.font.SysFont("lucidaconsole", 14)
text = font.render("Thanks for playing!", True,
self.white) self.gameDisplay.blit(text, (600, 520))
Program
import
pygame
import math
import sys
pygame.init()
screen = pygame.display.set_mode((600,
300)) pygame.display.set_caption("Elliptical
while(True):
event.type == pygame.QUIT:
sys.exit()
xRadius = 250
yRadius = 100
pygame.display.flip()
clock.tick(5)
OUTPUT:
Result
Thus the above Python program using exception handling are executed and verified successfully.