0% found this document useful (0 votes)
69 views

Python Lab Manual

python lab manual for R-21 students

Uploaded by

kavitha Mookkan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views

Python Lab Manual

python lab manual for R-21 students

Uploaded by

kavitha Mookkan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 85

GE3171 PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY

COURSE OBJECTIVES:

□ To understand the problem solving approaches.


□ To learn the basic programming constructs in Python.
□ To practice various computing strategies for Python-based solutions to real world
problems.
□ To use Python data structures – lists, tuples, dictionaries.
□ To do input/output with files in Python.

EXPERIMENTS:

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 a motorbike, Weight of a steel bar, compute Electrical Current in Three Phase AC
Circuit, etc.)

2. Python programming using simple statements and expressions (exchange the values of
two variables, circulate the values of n variables, distance between two points).

3. Scientific problems using Conditionals and Iterative loops. (Number series, Number
Patterns,pyramid pattern)

4. Implementing real-time/technical applications using Lists, Tuples. (Items present in a


library/Components of a car/ Materials required for construction of a building –operations of
list & tuples)

5. Implementing real-time/technical applications using Sets, Dictionaries. (Language,


components of an automobile, Elements of a civil structure, etc.- operations of Sets
& Dictionaries)

6. Implementing programs using Functions. (Factorial, largest number in a list, area of


shape)

7. Implementing programs using Strings. (reverse, palindrome, character count, replacing


characters)

8. Implementing programs using written modules and Python Standard Libraries


(pandas, numpy. Matplotlib, scipy)

9. Implementing real-time/technical applications using File handling. (copy from one file
to another, word count, longest word)
10. Implementing real-time/technical applications using Exception handling. (divide by zero
error, voter’s age validity, student mark range validation)

11. Exploring Pygame tool.

12. Developing a game activity using Pygame like bouncing ball, car race etc.

COURSE OUTCOMES:

On completion of the course, students will be able to:


CO1: Develop algorithmic solutions to simple computational problems
CO2: Develop and execute simple Python programs.
CO3: Implement programs in Python using conditionals and loops for solving problems.
CO4: Deploy functions to decompose a Python program.
CO5: Process compound data using Python data structures.
CO6: Utilize Python packages in developing software applications.
EX NO:1(a)
Date: ELECTRICITY BILLING

AIM:

To develop flowchart for Electricity Billing.

ALGORITHM:

Step 1: Start the program


Step 2: Get the input as unit, the unit consumed by the customer
Step 3: If the unit consumed less or equal to 50 units, calculates the total amount
of consumed =units*0.05.
Step 4: If the unit consumed between 50 to 150 units, calculates the total amount
of consumed=25+(unit*0.05)*0.75 s_charge =amount*0.20
Step 5: If unit consumed between 150 to 250 units, calculates total amount of
consumed=100+(unit-150)*1.20 s_charge =amount*0.20
Step 6: If unit consumed is above 250 units, the total amount of consumed= 220+ (unit-
250)*150
Step 7: Print the total amount.
Step 8: Stop the program.
FLOWCHART:

RESULT

Thus the flowchart for Electricity Billing was Successfully done.


EX NO: 1(b)
Date: RETAIL SHOP BILLING

AIM:
To develop a flowchart for Retail Shop Billing.

ALGORITHM:

Step 1: Start the program


Step 2: Read the product id and quantity
Step 3: Check with database if the product available and fetch the price of the
product Step 4: Calculate the total cost of each items purchased.
Step 5: Calculate sales tax as total cost * 5%
Step 6: Calculate bill amount as total cost + sales tax Step 7: Display bill amount
Step 8: Stop the program
FLOWCHART:

RESULT:

Thus the flowchart For Retail Shop Billing was successfully done.
EX NO: 1(c)
Date: SINE SERIES

AIM:
To develop a flowchart for Sine series.

ALGORITHM:
Step 1: Start the program
Step 2: Take in the value of x in degrees and the number of terms and store it in separate
variables.
Step 3: Pass these values to the sine function as arguments.
Step 4: Define a sine function and using a for loop, first convert degrees to radians.
Step 5: Then use the sine formula expansion and add each term to the sum variable.
Step 6: Then print the final sum of the expansion.
Step 7: Stop the program
FLOWCHART:

RESULT:

Thus the flowchart for sine series was successfully done


EX NO: 1(d) WEIGHT OF A MOTORBIKE
Date:

AIM:
To develop a flowchart for weight of a motorbike.

ALGORITHM:

Step1: Start the program


Step2: Read the size of the motorbike in CC
Step3: Check whether the size of the motor bike is less than or equal to 300 cc,
if so, Print Average weight is 350 pounds otherwise go to step 4.
Step4: Check whether the size of the motor bike is less than or equal to 500 cc,
if so, Print Average weight is 410 pounds otherwise go to step 5.
Step5: Check whether the size of the motor bike is less than or equal to 900cc,
if so, Print Average weight is 430 pounds otherwise go to step 6
step 6: Check whether the size of the motor bike is equal to 1100 cc,
if so, Print Average weight is 500 pounds otherwise go to step 7
step 7:Print Average weight is 600 pounds.
Step 8: Stop the program
FLOWCHART:

RESULT:
Thus the flowchart for finding the type of the motorbike using its weight was
successfully done.
EX NO: 1(e) WEIGHT OF A STEEL BAR
Date:

AIM:

To develop a flowchart for weight of a steel bar.

ALGORITHM:

Step 1: Start
Step 2: Get the diameter
Step 3: Compute the weight of steel bar by calculating D2/162
Step 4: Print the Result
Step 5: Stop

FLOWCHART:

RESULT:

Thus the flowchart for calculating the weight of the steel bar was successfully done.
EX NO: 1(f)
Date: COMPUTE ELECTRICAL CURRENT IN THREE PHASE AC
CIRCUIT

AIM:
To develop a flowchart to compute Electrical Current in three phase AC circuit.

ALGORITHM:

Step 1: Start the program


Step 2: Get the voltage as V and impedence as Z
Step 3: Calculate the current using current=voltage /impedance
Step 4: Print the current
Step 5: Stop the program

FLOWCHART:

RESULT:

Thus the flowchart to compute electrical current in three phase AC circuit was
successfully done.
EX NO: 2(a)
Date: EXCHANGE THE VALUE OF TWO VARIABLES

AIM:
To write a python program for exchange the value of two variables.

ALGORITHM:

Step 1: Start the program


Step 2: Define a and b variables
Step 3: Swap the two values using the temp variable
Step 4: Print a and b
Step 5: Stop the program

PROGRAM:

a = input(“Enter value of a:”)


b = input(“Enter value of b:”)
c=a
a=b
b=c
print(“The value of a after swapping:”,a)
print('The value of b after swapping:”,b)

OUTPUT:

Enter value of a: 5
Enter value of b: 2
The value of a after swapping: 2
The value of b after swapping: 5

RESULT:
Thus the python program to exchange the value of two variables was successfully
executed and verified.
EX NO: 2(b)
Date: CIRCULATE THE VALUES OF N VARIABLES

AIM:
To write a python program to circulate the values of n variables.

ALGORITHM:

Step 1: Start the program


Step 2: Get the number of values to be inserted.
Step 3: Get the integer values
Step 4: Circulate the values of n variable using for loop
Step 5: Print the result
Step 6: Stop the program

PROGRAM:

a=list(input("Enter the list"))


print(a)
for i in range(1,len(a),1):
print(a[i:]+a[:i])

OUTPUT:

Enter the list [1,2,3,4,5]


[1, 2, 3, 4, 5]
[2, 3, 4, 5, 1]
[3, 4, 5, 1, 2]
[4, 5, 1, 2, 3]
[5, 1, 2, 3, 4]

RESULT:
Thus the python program to circulate the values of n variables was successfully
executed and verified.
EX NO: 2(c)
Date: CALCULATE THE DISTANCE BETWEEN TWO POINTS

AIM:
To write a python program to calculate the distance between two points.

ALGORITHM:

Step 1: Start the program


Step 2: Get the value of the co-ordinate points as x1, y1, x2, y2
Step 3: Calculate the distance using the corresponding formula
Step 4: Print the result
Step 5: Stop the program

PROGRAM:

import math
x1=int(input(“Enter value of x1:”))
y1=int(input(“Enter value of y1:”))
x2=int(input(“Enter value of x2:”))
y2=int(input(“Enter value of y2:”))
distance = math.sqrt(((x2-x1)**2) + ((y2-y1)**2) )
print ("Distance between given points is", distance)

OUTPUT:
Enter value of x1: 2
Enter value of y1: 3
Enter value of x2: 4
Enter value of y2: 5
('Distance between given points is', 2.8284271247461903)

RESULT:

Thus the python program to calculate the distance between two points was
successfully executed and verified.
EX NO: 3(a) NUMBER SERIES
Date:

AIM:
To write a python program to perform the sum of series 1+2+3+ N.

ALGORITHM:
Step 1: Start the program
Step 2: Get a value from the user and store it in a variable n.
Step 3: Set for loop with i value ranges from 1 to n.
Step 4: Print the value of i and ‘+’ operator while appending the value of i to a list.
Step 5: Find the sum of elements in the list.
Step 6: Print ‘=’ followed by the total sum.
Step 7: Stop the program

PROGRAM

OUTPUT:

RESULT

Thus the python program to perform the sum of series 1+2+3+ N was
successfully executed and verified.
EX NO: 3(b) SQUARE NUMBER PATTERN
Date:

AIM:
To write a python program to perform the sum of series 1+2+3+ N.
ALGORTIHM:

Step1: Start the program

Step 2: Use a for loop where i ranges between the 0 and n-1 with a increment of 1 with each
iteration.

Step 2.1: Use a for loop where j ranges between of 0 and n-1 with a increment of 1 for ith
iteration

Step 2.1.1. Print the numbers for every iteration with new line

Step3 : Stop the program.

PROGRAM:

OUTPUT:

12345
12345
12345
12345
12345

RESULT:
Thus the python program to perform the Square Number pattern was successfully
executed and verified.
EX NO: 3(c) LEFT TRIANGLE NUMBER PATTERN
Date:

AIM:
To write a python program to perform the Left Triangle Number Pattern
ALGORTIHM:

Step1:Start the program

Step2:Get the n value from user.

Step 2:Use a for loop where i ranges between the 0 and n+1 with a increment of 1 with each
iteration.

Step 2.1: Use a for loop where j ranges between of 1 and i+1 with a increment of 1 for
ith iteration

Step 2.1.1: Print the numbers for every iteration with new line

Step3: Stop the Program.

PROGRAM:

OUTPUT:

RESULT:

Thus the python program to perform the Left Triangle Number pattern was
successfully executed and verified.
EX NO: 3(d) PYRAMID PATTERN WITH STARS
Date:

AIM:
To write a python program to perform the Left Triangle Number Pattern
ALGORTIHM:

Step1: Start the program


Step 2: Get value from the user and store it in a variable n.
Step 3: Use a for loop where the value of i ranges between the values of 0 and n-i with an
increment of 1 with each iteration.
Step 3.1: Use a for loop where the value of j ranges between the values of 0 and (n-i-1)
with a increment of 1 for ith iteration
3.1.1. Creating an empty space for display the Stars
Step 3.2: Use a for loop where the value of k ranges between the values of 0 and (2 * i + 1)
with an increment of 1 for ith iteration
3.2.1 print the stars in the created empty spaces
Step 4: Stop the program
PROGRAM:

OUTPUT:

RESULT

Thus the python program to perform the Pyramid Star pattern was successfully
executed and verified.
EX NO: 4(a) LIBRARY MANAGEMENT USING LIST
Date:

AIM:

To write a python program to perform library management.

ALGORTIHM:

Step1: Start the program

Step 2: Get the value for number of books and details from the user and store it in a List
library _books.

Step 3: check whether the book is present in the defined list. If yes, display the details of the
book.

Step 4: Use if cases to work on each module

If choice equal to 1,Access the book informations.


If choice is equal to 2 , update the price of concern book.
If choice is equal to 3, remove the book from the list else Exit

Step 5: Stop the program


PROGRAM:
OUTPUT:

RESULT

Thus the python program to perform library management was successfully executed
and verified
EX NO: 4(b) COMPONENTS OF A CAR USING TUPLE
Date:

AIM:

To write a python program to find Components of a car using Tuple.

ALGORTIHM:

Step1: Start the program


Step 2: Read the Stocks and its Quantity details and store it in a variable Old_stocks
Step 3: Display the stock list to the user.
Step4: Get the user demand
Step4.1: If it available, show the available stocks else show not available
Step5: Update the stocks list by adding new items.
Step 6: Stop the program
PROGRAM:
OUTPUT:

RESULT

Thus the python program to find Components of a car using Tuple.was successfully executed
and verified
EX NO: 4(c) MATERIALS REQUIRED FOR CONSTRUCTION OF A
Date: BUILDING USING TUPLE

AIM:

To write a python program to find materials required construction of a Building using


tuple.

ALGORTIHM:

Step1: Start the program


Step 2: Read the materials Required for constructing a building
Step 3: Display the materials.
Step4: Get the user demand
Step4.1: If it available, show the available stocks else show not available
Step 5: Stop the program
PROGRAM:

OUTPUT:

RESULT:

Thus the python program to find materials required for construction of a building
using tuple was successfully executed and verified.
EX NO: 5(a) COMPONENTS OF AN AUTOMOBILE USING SET
Date:

AIM:

To write a python program to find Components of Automobile.


ALGORTIHM:

Step1: Start the program


Step 2: Read the Automobile accessories and stored it in Set.
Step 3: Display the automobile accessories.
Step4: Get the user Requirements
Step4.1: If it available, show the available automobile accessories else print not
available.
Step 5: Use if cases to work on each module
Case 1- for Accessing Automobile accessories information
Case 2- for Removing for Automobile accessories information
Case 3- for updating new parts to the stock
Case 4- EXIT

Step 6: Stop the program


PROGRAM:
OUTPUT:

RESULT:
Thus the python program to find Components of Automobile using Set was
successfully executed and verified.
EX NO: 5(b) ELEMENTS OF A CIVIL STRUCTURE USING DICTIONARY
Date:

AIM:

To write a python program to perform elements of a civil structure using dictionary


ALGORTIHM:
Step1: Start the program
Step 2: Read the elements of Civil Structures and stored it in dictionary.
Step 3: Display the elements of Civil Structures.
Step 4: Updating the element corresponding Position.
Step 5: Adding new elements to the Dictionary.
Step 5: Removing the element from the Dictionary.

Step 6: Stop the program.


PROGRAM:

OUTPUT:

RESULT:
Thus the python program to perform elements of a civil structure using dictionary was
successfully executed and verified.
EX NO:6(a)
Date: Find Factorial of Number Using Recursion

Aim:

To Write a Python Program to Find Factorial of Number Using Recursive function

Algorithm:

Step1: Start the program


Step2: Read the number from the user and store it in a variable as num.
Step 3: If num <0 ,print the num is negative
Step 3.1 elif the num is equal to zero then factorial is 1
Step 3.2: else pass the number as an argument to a recursive factorial function
Step 4: Call the function recursively with the number minus 1 multiplied by the number
itself.
Step 5. Then return the result and print the factorial of the number.
Step 6.Stop the Program.
Program:

Output:

RESULT:
Thus the python program to find the Factorial of Number Using Recursive function is
successfully executed and verified
EX NO:6(b)
Date: Largest Number in a List

Aim:

To Write a Python Program to Find Largest Number in a List using function

Algorithm:

Step1: Start the program


Step2: Read the number from the user and store it in a variable as num.
Step3: Read the element for the list using for loop until, the end of the elements in a list.
Step4: Pass the list as an argument to function named find_max.
Step5:Set first element as max=list[0]
Step6:for a in range 0 to n-1
Step6.1: check if list[i]>max
then assign max=list[i]
Step7: Return the max and print the result.
Step8: Stop the program.
Program:

Output:

RESULT
Thus the python program to Find Largest Number in a List using function is
successfully executed and verified.
EX NO:6(c)
Date: Area of Shape

Aim:
To write a Python Program to find area of shape (Square, rectangle, circle, triangle,
parallelogram) using function.
Algorithm:

Step1:Start the program.


Step2:Define the Functions for each Shapes.
Step3:Get the input and calculate the area by using corresponding Formula for all Shapes.
Step4:Print the Area
Step5:Stop the program
Program:
OUTPUT

RESULT

Thus the python program to find area of shape (Square, rectangle, circle, triangle,
parallelogram) using function was successfully executed and verified.
EX NO: 7(a)
Date: REVERSE OF A STRING

AIM:
To write a python program to perform Reverse operation in a string.

ALGORTIHM:

Step1: Start the program


Step2: Get the input from the user
Step3: Use slice() to emulate the slicing [::-1] to reverse the given string.
Step4: Print the output
Step5: Stop the program.
PROGRAM:

OUTPUT:

RESULT:
Thus the python program to perform Reverse operation in a string was successfully
executed and verified.
EX NO: 7(b) PALINDROME OF A STRING
Date:

AIM:
To write a python program to implement palindrome of a string.

ALGORITHM:
Step 1: Start the program
Step 2: Get the input from the user to check for palindrome
Step 3: Using slice operation [start:end:step],check whether the string is reversed or not.
Step 4: If yes, it prints a palindrome else, not a palindrome.
Step 5: Print the output
Step 6 : Stop the program
PROGRAM:

OUTPUT:

RESULT:

Thus the python program to implement palindrome of a string was successfully


executed and verified.
EX NO: 7(c) CHARACTER COUNT IN A STRING
Date:

AIM:
To write a python program to count number of characters in a string.

ALGORITHM:
Step 1: Start the program
Step 2: Get the input string from the user
Step 3: Define and initialize a variable total as 0.
Step 4: Iterate through the string till the end and for each character except spaces, increment
the count by 1.
Step 5: Print the total number of characters in a string.
Step 6 : Stop the program
PROGRAM:

OUTPUT:

RESULT:

Thus the python program to count the number of characters in a string was
successfully executed and verified
EX NO: 7(d) REPLACING CHARACTERS IN A STRING
Date:

AIM:
To write a python program to Replace characters in a string

ALGORITHM:
Step 1: Start the program
Step 2: Get the input string from the user
Step 3: Use str.replace(old, new) to replace all occurrences of a character old with the
desired character new
Step 6: Print the replaced string
Step 7 : Stop the program.
PROGRAM:

OUTPUT:

RESULT
Thus the python program to Replace character in a string was successfully executed
and verified.
EX NO:8(a)
Date: GENERATING A DATAFRAME USING PANDAS

AIM:
To write a python program to framing a data using Pandas.

ALGORITHM:

Step 1: Start the program


Step 2: import the pandas module
Step 3: Create a dictionary with key pair value of name, age.
Step 4: Create a Data Frame by using pandas
Step 5: Print the Data Frame report.
Step 6: Stop the program.
PROGRAM:

OUTPUT:

RESULT:
Thus the python program to framing a data using Pandas.was successfully executed
and verified
EX NO:8(b)
Date: MULTIPLY MATRICES USING NUMPY

AIM:
To write a python program tofind multiply matrices using numpy.

ALGORITHM:

Step 1: Start the program


Step 2: import the numpy module
Step 3: Define two matrices M1,M2 by using array object.
Step 4: Create a resultant matrix named M3.
Step 5: Stop the program.
PROGRAM:

OUTPUT:

RESULT:

Thus the python program to multiply matrices using numpy was successfully executed
and verified.
EX NO:8(c)
Date: GENERATING A PIECHART USING MATPLOTLIB

AIM:
To write a python program to generating a piechart using matplotlib

ALGORITHM:

Step 1: Start the program


Step 2: import the numpy,matplotlib, module and necessary builtin functions for piechart
Step 3 :Creating a car _dataset for building piechart by using list.
Step 4: Set the parameters for figure size, chart type of function figure in car_dataset.
Step 5: Plot the pie chart for car_dataset by using pie ( ).
Step 6 : Stop the program.
PROGRAM:

OUTPUT:

RESULT:

Thus the python program to build a piechart using matplotlib successfully was
executed and verified
EX NO:8(d)
Date: GENERATING A WAVEFORM USING SCIPY

Aim:
To write a Python Program to generate linear waveform using scipy library.

Algorithm:

Step1: Start the Program


Step 2: import the numpy,matplotlib module and necessary builtin functions for generating
linear waveform.
Step 3:Using scipy.signal ,subfunction Chrip is used to generate waveform(t, f0, t1, f1,
method=’linear’, phi=0, vertex_zero=True) where,

Step 4: Define the plot function with parameters time ,linear values to generating linear
Waveform .
Step 5: Stop the program.
PROGRAM:

OUTPUT:

RESULT:
Thus the python program to generate waveforms using scipy library successfully was
executed and verified.
EX NO:9(a)
Date: FILE HANDLING-COPY FROM ONE FILE TO ANOTHER

Aim:

To write a Python Program to copy from one file to another.


Algorithm:

Step1: Start the Program


Step 2: Create a list named as a_list, add content to the list.
Step 3: Open one file called myfile.txt in read mode.
Step 4: Open another file myfileout.txt in write mode.
Step 5: Read each line from the input file and write it into the output file.
Step 6: Stop the program.
PROGRAM:

OUTPUT:

RESULT

Thus the python program to copy from one file to another was successfully executed
and verified.
EX NO:9(b)
Date: FILE HANDLING -WORD COUNT FROM A FILE

AIM:

To write a Python Program find to word count from a file.


ALGORITHM:

Step1: Start the Program


Step 2: Create a list named as a_list.
Step 3: Open a input file called myfile.txt in read mode.
Step 4: Append the list to the input_file and close the file.
Step 5: Open file myfilein.txt in write mode.
Step 6: Read the input file and split the content of a file into words by using split( )
Step 7: Find the number of words in a input file by using len().
Step 8: Stop the program.
PROGRAM:

OUTPUT:

RESULT

Thus the python program to find word count from a file was successfully executed and
verified.
EX NO:9(c) FILE HANDLING –FINDING LONGEST WORD IN A FILE
Date:

AIM:

To write a Python Program find to longest word in a file.


ALGORITHM:

Step1: Start the Program


Step 2: Create a list named as a_list.
Step 3: Open a input file called myfile.txt in read mode.
Step 4: Append the list to the input_file and close the file.
Step 5: Open file myfilein.txt in read mode.
Step 6: Read the input file ,find the max length of word in a file
Step 7: Print the longest word in a file.
Step 8: Stop the program.
PROGRAM:

OUTPUT:

RESULT

Thus the python program to find longest word in a file was successfully executed and
verified.
EX NO:10(a)
Date: EXCEPTION HANDLING-DIVIDE BY ZERO ERROR

AIM:

To write a Python Program to find Divide By zero error by Using Exception Handling.

ALGORITHM:

Step1: Start the Program


Step 2: Get inputs from the user, two numbers.

Step 3: If the entered data is not integer, throw an exception.

Step 4: If the remainder is 0, throw divide by zero exception.

Step 5: If no exception is there, return the result.

Step 6: Stop the program.


PROGRAM:

OUTPUT
Run 1:

Run 2:

Run 3:

RESULT

Thus the python program to find Divide By zero error by Using Exception Handling
was successfully executed and verified.
EX NO:10(b) Exception Handling-Voter’s Age Validity
Date:

AIM:
To write a Python Program to find Voter’s Age Validity by Using Exception
Handling.
ALGORITHM:

Step1: Start the Program


Step 2: Get input from the user, age.

Step 3: If the entered data is not integer, throw an exception.

Step 4: If no exception is there, print eligible to vote or not eligible to vote.

Step 5: Stop the program.


PROGRAM:

OUTPUT:
Run 1:

Run 2:

Run 3:

RESULT

Thus the python program to find Voter’s Age Validity by Using Exception Handling
was successfully executed and verified.
EX NO:10(c) Exception Handling- Student Mark Range Validation
Date:

AIM:
To write a Python Program to find student mark range validation by Using Exception
Handling.

ALGORITHM:

Step1: Start the Program


Step 2: Get input from the user, age.

Step 3: If the entered data is less than 0 , throw an exception as Value Too Small Error.

Step 4: If the entered data is greater than 100, throw an exception as Value Too High Error.

Step 5: If no exception is there, print the mark .

Step 5: Stop the program


Program:

OUTPUT

RESULT

Thus the python program to to find student mark range validation by Using Exception
Handling.was successfully executed and verified.
EX NO:11 EXPLORING PYGAME TOOL
Date:

AIM:
To explore a Pygame Tool.
PROCEDURE:

 Game development is one of the most common reasons to start to study


programming. With me it was not different, despite not following the game
developer path, this was always a field that caught my attention.

 I’m creating this series of posts to learn more about the game development
basics and to share my discoveries with everyone. I’ll use 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.

 To reach this goal I’ll start with Structured Programming focused at the basics
of game development and pygame to make it more comfortable for beginners.
As the series goes I’ll refactor the code to introduce Object Oriented
Programming concepts.

 The code used on this series will be running at Python 3

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](http://www.pygame.org/wiki/GettingStarted#Pygame 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 hello.py with the following content:

1 # -*- coding: utf-8 -*-


2
3 import time
4
5 import pygame
6
7 pygame.init()
8
9 screen = pygame.display.set_mode([640, 480])
10
11 pygame.display.set_caption('Hello World')
12
13 screen.fill([0, 0, 0])
14
15 pygame.display.flip()
16
17 time.sleep(5)
 Then we just need to run it:

 $ python hello.py
 So the result will be this:
 It’s still far from a game, but we can see some basic concepts to be discussed.

 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 pygame.init() starts all modules that need initialization inside
pygame.

 At pygame.display.set_mode we create an area for the game window at the


size of 640x480 pixels, followed by pygame.display.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 pygame.display.flip 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.

DRAWING ON SCREEN
 During a game lifetime, we are constantly drawing on the screen. Now that we learned
how to create a program with pygame it’s time to start to draw.

DRAWING AXIS

 Going back to math classes at high school we were introduced to the Cartesian coordinate
system. It is basically one bidimensional plane oriented by the axis x and y where
the x values grow from left to right while y grows from bottom to top:
 At pygame there’s a little change, the drawing space will use the
coordinates x and y too but the y axis will follow the opposite direction from the
cartesian coordinate system, y will grow from top to bottom and the visible area of the
screen will be located starting from the point x=0 and y=0 as the top left corner of
your program window going until the size defined at the
command pygame.display.set_mode((x, y)):

LET’S DRAW!

 Start by creating a file draw.py with the following content:

1 import time
2
3 import pygame
4
5 # defining the colors
6 BLACK = (0, 0, 0)
7 WHITE = (255, 255, 255)
8 BLUE = (0, 0, 255)
9 GREEN = (0, 255, 0)
10 RED = (255, 0, 0)
11
12 pygame.init()
13
14 screen = pygame.display.set_mode((640, 480))
15 # loading the font to be used at drawing time
16 font = pygame.font.SysFont(None, 55)
17
18 pygame.display.set_caption('Drawing')
19
20 screen.fill(BLACK)
21
22 # drawing at the surface
23 pygame.draw.line(screen, WHITE, [10, 100], [630, 100], 5)
24 pygame.draw.rect(screen, BLUE, [200, 210, 40, 20])
25 pygame.draw.ellipse(screen, RED, [300, 200, 40, 40])
26 pygame.draw.polygon(screen, GREEN, [[420, 200], [440, 240], [400, 240]])
27
28 pygame.display.flip()
29
30 time.sleep(5)
31
32 screen.fill(BLACK)
33
34 # writing pygame at the buffer
35 text = font.render('pygame', True, WHITE)
36 # coping the text to the screen
37 screen.blit(text, [250, 200])
38
39 pygame.display.flip()
40
41 time.sleep(5)

 The program starts by defining the values of the colors that will be used later.
Following it initializes pygame like at the previous post and then it loads the font
at pygame.font.SysFont to be ready to use later.

 After filling the screen surface with the black color some of the drawing functions
available at pygame.draw are used:

 line: draws a line receiving as parameters the surface following by its color, a list with
the starting and the end coordinates, and the line thickness in pixels.
 rect: draws a rectangle receiving as parameters the surface following by its color and
a list with the starting x position, starting y position, width, and height.
 ellipse: draws a circumference receiving as parameters the surface following by its
color and a list with the same structure of rect.
 polygon: draws a polygon receiving as parameters the surface following by its color
and a list with the coordinates from the polygon vertices.
 After that pygame.display.flip() refreshes the entire drawing area of the
surface screen, following by an interval of 5 seconds.

 After the sleep it fills the surface with black and the text that will be written is
defined using the font.render method where the first parameter is
the string pygame, then the value True that activate the anti-alias that smooths the
text, and as third parameter white as the color of the font. This method creates an
intermediary surface with the text that will be passed to the screen surface with the
method blit that receives as parameter the surface that will be copied and its
position at the surface screen.

GAME LOOP
 Now that we learned how to draw on the screen (previous post) would be good that
our game keeps running until someone closes it, and to do that we will use one of the
basic concepts of game development with is the Game Loop.

Concept

 The concept of loop is something very common at computing, it is nothing but a


sequence of actions and decision makings that repeats inside on a cycle. At a low
level, we have the CPU that works in cycles of arithmetic operations managed by
the clock rate, at Operating Systems there is a loop that manages the time that each
process have with the CPU and that check for user inputs, and at web servers we use
a loop to check if someone made a request to a page that will be processed and
returned as response. With games, it shouldn’t be different.

 The loop used at game development is called Game Loop and is a key component at
the structure of a game. On a simplified manner, we have the following structure:
During the execution the game is always:

 Input processing that is done by detecting events created by input devices like a
keyboard or a mouse.

 Game update with the events processed and some internal mechanics like game
gravity, collision detection, and others the game variables are updated.

 Drawing the result of all this processing will be drawn on the screen to give visual
feedback to the user.

 Unlike an event loop at a desktop application where the program keeps waiting until
you make an input, the game loop updates the game even if you don’t provide any
input because there are a lot of things happening that not require user input like music,
physics, enemy A.I., and so forth.

 Another important point that isn’t present above is the time step control that keeps the
game update rate smooth between different computers with different processing
powers. But that is a topic for a future post.

IMPLEMENTATION

To show the game loop running we will write a program that draws a ball that bounces
through the screen:

1 import pygame
2
3 # define colors
4 BLACK = (0, 0, 0)
5 WHITE = (255, 255, 255)
6 BLUE = (0, 0, 255)
7 GREEN = (0, 255, 0)
8 RED = (255, 0, 0)
9
10 pygame.init()
11
12 screen = pygame.display.set_mode((640, 480))
13
14 pygame.display.set_caption('Game Loop')
15
16 # the ball variables
17 position_x = 300
18 position_y = 200
19 velocity_x = 1
20 velocity_y = 1
21
22 # starting the game loop
23 while True:
24 # INPUT PROCESSING
25
26 # catch the events
27 event = pygame.event.poll()
28 # if the QUIT event is caught (when you click on the x to close the window)
29 if event.type == pygame.QUIT:
30 # end the loop and finish the program
31 break
32
33 # GAME UPDATE
34
35 # change the ball position
36 position_x += velocity_x
37 position_y += velocity_y
38
39 # change the x direction at the corners
40 if position_x > 600:
41 velocity_x = -1
42 elif position_x < 0:
43 velocity_x = 1
44
45 # change the y direction at the corners
46 if position_y > 440:
47 velocity_y = -1
48 elif position_y < 0:
49 velocity_y = 1
50
51 # DRAWING
52
53 # fill the background with black
54 screen.fill(BLACK)
55
56 # draw the ball
57 pygame.draw.ellipse(screen, RED, [position_x, position_y, 40, 40])
58
59 # update the screen
60 pygame.display.flip()

 The game loop is created with while True: and will run indefinitely doing the game
steps of input, processing and drawing at every cycle.

 At the input processing step we use pygame.event.poll() to catch an event at the queue and
check if it is an event to end the program. If it is we use break to end the loop and
finish the program execution.

 During the game update step we move the ball on the axis, x and y, checking if it collides
with the corners and if that happens we change its direction.

 And finally, at the drawing step we use the methods from the previous post to draw the
ball on the screen.

 Note that we always fill the background with black before to draw the ball, if we don’t
do that, the ball will leave a trace on the screen from the previous draws
EX NO:12(a) BOUNCING BALL USING PYGAME
Date:

AIM:

To develop a Bouncing Ball game using pygame .


ALGORITHM:

Step1: Start the Program


Step 2: Import the necessary files for the implementation of Pygame.

Step 3: Set the display mode for the screen using

windowSurface=pygame.display.set_mode((500,400),0,32)

Step 4: Now set the display mode for the pygame to bounce

pygame.display.set_caption(“Bounce”)

Step 5: Develop the balls with necessary colors.

BLACK=(0,0,0)

WHITE=(255,255,255)

RED=(255,0,0)

GREEN=(0,255,0)

BLUE=(0,0,255)

Step 6: Set the display information info=pygame.display.Info()

Step 7: Set the initial direction as down.

Step 8: Change the direction from down to up.

Step 9: Then again change the direction from up to down.

Step 10: Set the condition for quit.

Step 11: Stop the Program.


PROGRAM:
OUTPUT:

RESULT

Thus the python program to develop bouncing ball using pygame was
successfully executed and verified.
EX NO:12(b) CAR RACE USING PYGAME
Date:

AIM:

To develop Car Race game using pygame .


ALGORITHM:

Step 1: Start the Program


Step 2: To install the Pygame library is, open command prompt or terminal on your computer
and then type one of the following commands in terminal:
 pip install pygame
Step 3: After installing Pygame, you can start to develop the game.
Step 4: Make a folder with name of “img” and put the necessary images (Download images:
https://drive.google.com/drive/folders/1jxzqPNtjGv7wJxgcrTKom9vW12lSui1u?usp=sharing)
Step 5: Create a file init .py in a directory of “img”, that can just be an empty file, but it can
also execute initialization code for the package or set the all variable.
Step 6: import the necessary Libraries pygame, time, random, These library are used to make
utilization of related functions.
Step 7: The gameplay is too simple all you have to do is just dodge the car from the other cars.
Here, the user has to dodge the car from the other cars in order to gain score points.
Step 8: By default, the Pygame window opens at the size of 800 pixels wide by 600 pixels high.
Step 9: You can customize the size of your window, there are two predefined variables you can
set, if you include WIDTH = 800 HIGH = 600. Pygame provides predefined functions to handle
the game loop normally performs.
Step 10: Define a necessary user defined functions that player has to be as quick as possible
because the more you score the point, faster will be the gameplay. Whenever the player touches
other cars, crashes or gets the car to the end of the display screen.
Step 11: A simple GUI is provided for the easy gameplay. The gameplay design is so simple that
user won’t find it difficult to use and navigate.
Step 12: In this game we will have three different states to the game stored in our
variable gameStatus : gameStatus == 0 # game is running, gameStatus == 1 # car crash,
gameStatus == 2 # game finished.
PROGRAM:
OUTPUT:

RESULT

Thus the python program to develop Car Race using pygame was successfully
executed and verified.

You might also like