Python Lab Manual
Python Lab Manual
COURSE OBJECTIVES:
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)
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)
12. Developing a game activity using Pygame like bouncing ball, car race etc.
COURSE OUTCOMES:
AIM:
ALGORITHM:
RESULT
AIM:
To develop a flowchart for Retail Shop Billing.
ALGORITHM:
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:
AIM:
To develop a flowchart for weight of a motorbike.
ALGORITHM:
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:
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:
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:
PROGRAM:
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:
PROGRAM:
OUTPUT:
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:
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:
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
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:
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
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:
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:
ALGORTIHM:
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.
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:
ALGORTIHM:
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:
ALGORTIHM:
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:
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:
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:
Algorithm:
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:
Algorithm:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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.
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:
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.
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:
HELLO WORLD
To make that let’s create a file called hello.py with the following content:
$ 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.
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.
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!
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 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:
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”)
BLACK=(0,0,0)
WHITE=(255,255,255)
RED=(255,0,0)
GREEN=(0,255,0)
BLUE=(0,0,255)
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:
RESULT
Thus the python program to develop Car Race using pygame was successfully
executed and verified.