GE3171 - PSPP Lab Manual Regulation 2021
GE3171 - PSPP Lab Manual Regulation 2021
Lab Manual
Prepared by Approved by
HoD/ IT
[Dr. R. Perumalraja]
1
Table of contents
Ex. Page
Name of the Exercise
No Number
Identification and solving of simple real life or scientific or technical problems,
and developing flow charts for the same. (Electricity Billing, Retail shop billing,
1 3
Sin series, weight of a motorbike, Weight of a steel bar, compute Electrical
Current in Three Phase AC Circuit, etc.)
Python programming using simple statements and expressions (exchange the
2 values of two variables, circulate the values of n variables, distance between two 8
points).
Scientific problems using Conditionals and Iterative loops. (Number series,
3 12
Number Patterns, pyramid pattern)
Implementing real-time/technical applications using Lists, Tuples. (Items present
2
Ex. No 1. Identification and solving of simple real life or scientific or technical problems,
and developing flow charts for the same.
Aim
The aim of this exercise is to identify and solve simple real life or scientific or technical
problems, and developing flow charts for the same.
Problems Given:
1. Electricity Billing
2. Retail Shop Billing
3. Sin Series
4. Weight of a Motorbike
5. Weight of a steel bar
6. Compute Electrical Current in Three Phase AC Circuit.
Concepts Involved
Algorithm
Algorithm is a step by step description for solving a problem.
It is a well defined computational procedure consisting of a set of instructions that takes
some value or set of values as input and produces some value or set of values as output.
There is a time and space complexity associated with each algorithm. The time
complexity specifies the amount of time required to perform a specific task. Space
complexity specifies the size of memory required by the algorithm.
Example: An algorithm to add two numbers entered by user:
Step 1: Start
Step 2: Declare variables a,b and c
Step 3: Read values of a and b
Step 4: Add a and b and assigns the result to c
c=a+b
Step 5: Display c
Step 6: Stop
3
Flow Chart
A flowchart is a graphical or symbolic representation of a process. Each step in the
process is represented by a different symbol and contains a short description of the
process step.
Example: Draw a flowchart to find product of two numbers A and B
Algorithm
1. Electricity Billing
Step 0: Start
When the unit is less than or equal to 100 units, calculate usage=uni*5
Step 5: Stop
4
2. Retail Shop Billing
Step 0: Start
Step 1: Declare the variables like item1, item2, item3, a1, a2, a3, and amount.
Step 2: Assign the values for a1, a2 and a3; a1=15, a2=120, a3=85.
Step 6: Stop.
3. Sin Series
Step 0: Start.
Step 2: Read the input like the value of x in radians and n where n is a number up to which we
want to print the sum of series.
sum=x;
power=1
num=num* (-x2);
power=power+2;
p=p*(power-1)*power
next=num/p;
5
Step 5: then sum=sum+next.
Step 6: Repeat the step 4 and step 5, looping 'n-1' times to get the sum of first 'n' terms of the
series.
Step 8: Stop.
4. Weight of a Motorbike
Motorcycle maximum load is the total weight the bike can carry including the rider,
passenger and any cargo.
Gross Vehicle Weight (GVW) of your motorcycle is the weight of the motorcycle itself
plus all engine fluids and full fuel, plus the maximum allowable weight of the rider and
passenger.
Motorcycle curb weight, or wet weight, is the weight of the motorcycle itself plus all
engine oils and full fuel.
Step 0: Start
weight=weightmotor+pr+eoff.
Step 5: Stop.
Weight of steel bar = (d2 /162)*length (Where d value in mm and length value in m)
Step 0: Start.
weight=(d2 /162)*length
P=√3 X pf X I X V
Step 0: Start
P=√3 X pf X I X V
Step 5: Stop
7
Ex. No 2. Python programming using simple statements and expressions
Aim
The aim of this exercise is to write python script for the given program using simple
statements and expressions and execute the same in Python IDLE (through Script or
Development Mode).
Problems Given
Concepts Involved
Variable: A variable is an identifier that refers to a value or variable is a memory location where
a programmer can store a value. Example: roll_no, amount, name etc.
Expression: It is a combination of values, variables and operators.
Statement: A statement is a unit of code that the Python interpreter can execute.
Reading Input:
Input often comes from the keyboard. It means the data entered by an end-user of
the program.
It has two key functions to deal with end user input called raw_input ( ) and
input().
raw_input:
o The raw_input([prompt]) function reads one line from standard input and
returns it as a string.
o This prompts the users to enter any string and it would display same
entered string on the screen.
o raw_input function is not supported by higher versions of Python for
Windows.
o Syntax:
var_name=raw_input(“<prompt input statement>”)
Example:
book_name=raw_input(“Enter your book name: “)
input:
o The input([prompt]) function is equivalent to raw_input, except that it
assumes the input as a valid Python expression and returns the evaluated
result. It has an optional parameter, which is the prompt string.
Syntax:
var_name=input(“<prompt expression or statement>”)
Example:
Name=input(“Enter your name”)
8
Import Module:
Module is a built in file containing python definitions and statements with the .py
extension, which implement a set of function.
Modules are imported from other modules using the import command.
When a module gets imported, it searches for the module and if found, python creates a
module object. If the named module cannot be found, ModuleNotFoundError will be
raised.
Syntax:
import modulename
Example:
import math
>>>math.ceil(30.56)
Output:
31
>>>math.floor(30.56)
Output:
30
SCRIPT:
OUTPUT
9
2.2. Circulate the values of n variables
OUTPUT
10
OUTPUT
11
Ex. No 3. Scientific Problems using Conditionals and Iterative Loops
Aim
The aim of this exercise is to write python script for the given program using conditionals
statements & iterative loops and execute the same in Python IDLE (through Script or
Development Mode).
Problems Given
1. Number Series
2. Number Patterns
3. Pyramid Patterns
Concepts Involved
Decision Making Statements:
Decision making constructs begins with a Boolean expression, an expression that returns
either True or False.
In Python programming, zero or null vales are assumed as false.
Decision making structures are necessary to perform an action or a calculation only when
a certain condition is met.
In Python we have the following types of decision making statements. They are:
o if statement
o if..else statements
o elif statements
o Nested if..elif..else statements
o Inline if
Conditional if statement
Syntax:
if Boolean expression:
Statement 1
Statement 2
…
Statement n
Alternative if…else statement
Syntax:
if test expression:
statements
else:
statements
Chained Condtional if..elif…else statements
Syntax:
if test_expression:
statements
12
elif test_expression:
statements
…..
else:
statements
Nested if…elif…else statements
Syntax:
if test_expression:
if test_expressioon_a:
statements
elif test_expression_b:
statements
else:
statements
elif test_expression:
statements
else:
statements
Inline if statements
Syntax:
do Task A if condition is true else do Task B
SCRIPT:
3.1 Number Series
OUTPUT
14
3.2 Number Patterns
OUTPUT
OUTPUT
15
Ex. No 4. Implementing real-time/technical applications using Lists and Tuples
Aim
The aim of this exercise is to write python script for implementing real time or technical
applications using Lists and Tuples and execute the same in Python IDLE (through Interactive
Mode).
Problems Given
Concepts Involved
Lists:
It is the simplest data structure in Python and is used to store a list of values.
It is an ordered sequence of values of any data type.
Values in the list are called as elements/items.
These are mutable and indexed/ordered.
To create a list, define a variable to contain an ordered series of items separated
by a comma. A square bracket is used to enclose the items.
Syntax:
my_list=[ ] #to create an empty list
To create a list of items:
my_list=[item1, item2, item3, item4]
For example:
num_list=[0, 5, 10, 15, 20]
string_ist=[“cat”, “dog”, “lion”]
Tuples:
It is another sequence data type similar to list.
A tuple consists of a number of values separated by commas and enclosed within
parenthesis.
Unlike list, the tuple values cannot be updated.
They are treated as read-only lists.
For example:
tuple1=(„abcd‟, 324, 3.2, „python‟, 3.14)
tuple2=(234, „abcd‟)
Operations of Lists and Tuples:
List:
Adding elements to the end of the list
Inserting items to a list
16
Changing elements of a list
Removing or deleting items from a list
Sorting items on a list
Reverse items on a list
Count ( ) method on a list
Tuple:
Changing, reassigning and deleting tuple
Tuple membership test
Tuple methods: count (x) and index (x)
SCRIPT
List with its operations:
4.1 Items present in a library
17
18
4.2 Components of a car
19
4.3 Materials required for construction of a building
20
Tuple with its operations:
4.1 Items present in a library
21
4.2 Components of a car
22
4.3 Materials required for construction of a building
23
Ex. No 5. Implementing real-time/technical applications using Sets and Dictionaries
Aim
The aim of this exercise is to write python script for implementing real time or technical
applications using Sets and Dictionaries and execute the same in Python IDLE (through
Interactive Mode).
Problems Given
1. Languages
2. Components of an automobile
3. Elements of a civil structure
To perform the operations of sets and dictionaries for the above mentioned problems
Concepts Involved
Sets:
A set is an unordered collection of unique elements.
Basic uses include dealing with set theory (which support mathematical
operations like union, intersection, difference, and symmetric difference) or
eliminating duplicate entries.
Dictionaries:
Python dictionary is a container of the unordered set of objects like lists.
The objects are surrounded by curly braces { }.
The items in a dictionary are a comma-separated list of key:value pairs where
keys and values are Python data type.
24
Each object or value accessed by key and keys are unique in the dictionary.
As keys are used for indexing, they must be the immutable type (string, number,
or tuple).
You can create an empty dictionary using empty curly braces.
25
SCRIPT
Set with its operations:
5.1 Language
26
5.3 Elements of a civil structure
27
Dictionary with its operations:
5.1 Language
28
5.2 Components of an automobile
29
5.3 Elements of a civil structure
30
Ex. No 6. Implementing programs using Functions
Aim
The aim of this exercise is to write python script for implementing the given programs
(scripts) using functions and execute the same in Python IDLE (through Script or Development
Mode).
Problems Given
1. Factorial
2. Largest number in a list
3. Area of shape
Concepts Involved
Function:
Function is a group of related statements that perform a specific task.
Functions help break our program into smaller and modular chunks. As our
program grows larger and larger, functions make it more organized and
manageable.
Furthermore, it avoids repetition and makes code reusable.
Syntax of function:
def function_name(parameters):
"""docstring"""
statement(s)
Example of a function:
def greet(name):
31
the person passed in as
parameter"""
Function Call
Once we have defined a function, we can call it from another function, program or
even the Python prompt. To call a function we simply type the function name with
appropriate parameters.
>>> greet('Paul')
Hello, Paul. Good morning!
Docstring
The first string after the function header is called the docstring and is short for
documentation string. It is used to explain in brief, what a function does.
Although optional, documentation is a good programming practice. Unless you
can remember what you had for dinner last week, always document your code.
In the above example, we have a docstring immediately below the function
header. We generally use triple quotes so that docstring can extend up to multiple
lines. This string is available to us as __doc__ attribute of the function.
For example:
>>> print(greet.__doc__)
This function greets to
the person passed into the
name parameter
Syntax of return
return [expression_list]
This statement can contain expression which gets evaluated and the value is
returned. If there is no expression in the statement or the return statement itself is not
present inside a function, then the function will return the None object.
For example:
>>> print(greet("May"))
Hello, May. Good morning!
None
32
How Function works in Python?
Types of Functions
Basically, we can divide functions into the following two types:
1. Built-in functions - Functions that are built into Python.
2. User-defined functions - Functions defined by the users themselves.
SCRIPT
6.1 Factorial
33
OUTPUT
34
OUTPUT
OUTPUT
35
Ex. No 7. Implementing programs using Strings
Aim
The aim of this exercise is to write python script for implementing the given programs
(scripts) using strings and execute the same in Python IDLE (through Script or Development
Mode).
Problems Given
1. Reverse
2. Palindrome
3. Character count
4. Replacing characters
Concepts Involved
String:
Strings are identified as a contiguous set of Unicode characters which may consist
of letters, numbers, special symbols or a combination of these represented within
the quotation marks.
It is an immutable data type, which means it can no longer be able to modify the
string once it is created.
Python language permits the use of single („), double (“) and triple („‟‟ or “””)
quote‟s to represent a string literal, making sure that the same type of quote
begins and ends that string.
Syntax:
o variable_name=”initial_string”
Example:
o student=”XXXYYYZZZ”
36
SCRIPT
7.1 Reverse
OUTPUT
37
7.2 Palindrome
OUTPUT
38
OUTPUT
OUTPUT
39
Ex. No 8. Implementing programs using written modules and Python Standard Libraries
Aim
The aim of this exercise is to write python script for implementing the given programs
(scripts) using written modules & Python Standard Libraries and execute the same in Python
IDLE (through Script or Development Mode).
Problems Given
1. pandas
2. numpy
3. matplotlib
4. scipy
Concepts Involved
Module:
A module allows you to logically organize your Python code and can define
functions, classes and variables. A module can also include a runnable code.
Math Module
1. Python math module is used to perform mathematical operations in python.
2. The math module is a standard module in Python and is always available.
3. We can use all functionality of math module by importing it
40
SCRIPT
8.1 pandas
Using pandas library, programmer can convert the given list into a series. In core python,
this problem will be solved by writing the long code, let‟s see how pandas do this.
OUTPUT
8.2 numpy
1. Introduces objects for multidimensional arrays and matrices, as well as functions that
allow to easily perform advanced mathematical and statistical operations on those
objects.
2. provides vectorization of mathematical operations on arrays and matrices which
significantly improves the performance.
3. many other python libraries are built on NumPy
Arrays
A numpy array is a grid of values, all of the same type, and is indexed by a tuple
of nonnegative integers. The number of dimensions is the rank of the array; the shape of
an array is a tuple of integers giving the size of the array along each dimension.
41
OUTPUT
8.3 matplotlib
42
OUTPUT
8.4 scipy
SciPy is Python Library used to solve scientific and mathematical problems. Built on
NumPy.
Allow Manipulation and Visualization of data.
43
44
OUTPUT
45
Ex. No 9. Implementing real-time/technical applications using File handling
Aim
The aim of this exercise is to write python script for implementing the given programs
(scripts) using file handling and execute the same in Python IDLE (through Script or
Development Mode).
Problems Given
Concepts Involved
File:
File is a named location on the system storage which records data for later access.
It enables persistent storage in a non-volatile memory i.e., Hard Disk.
Generally we divide files in two categories, text file and binary file. Text files are
simple text whereas; the binary files contain binary data which is only readable by
computer.
File Operations:
In Python, there is no need for importing external library to read and write files.
Python provides a built-in function for opening, writing and reading files. Hence,
in Python there are four basic file-related operations.
They are:
o Opening a file
o Reading from a file
o Writing to a file Process data
o Closing a file
Syntax:
Opening a file:
fileObject = open(file_name[, access_mode] [, buffering])
Where,
file_name It is a string value which contains the name of the file to access.
access_mode It determines the mode (read, write, append, etc.,) in which
the file has to be opened. It is an optional parameter the read ® mode is the
default file access mode.
buffering When the buffering value is set to 0, no buffering occurs. If it is
set to 1, line buffering is performed when accessing a file.
46
If the buffering value is an integer greater than 1, action is performed with the
indicated buffer size. If it is negative, the buffer size is the system default
behavior.
Different modes for opening a file:
While opening a file, we can specify whether to read (r), write (w) or append
(a) data to the file and also to specify whether to open in text or binary mode.
The default way of opening is in read (text mode). In text mode, we get strings
while reading from the file. In binary mode, it returns bytes and are used with
non-text files like .jpeg or .exe file.
The different modes for opening a file are as follow:
o r default mode for opening a file in read only format.
o rb It opens the file for read only purpose in binary format.
o r+ It opens a file for both reading and writing purpose in text
format.
o rb+ It opens a file for both reading and writing purpose in binary
format.
o w It opens a file for write only purpose in text format.
o wb It opens a file for write only purpose in binary format.
o w+ It opens a file for both reading and writing purpose in text
format.
o wb+ It opens a file for both reading and writing purpose in binary
format.
o a It opens a file for appending the data to the file.
o ab It opens a file for appending the data in binary format.
o a+ It opens a file for both appending and reading data to and from
the file.
o ab+ It opens a file for both appending and reading data in binary
format.
Example:
# Open file in read mode, the default mode:
>>> file = open(“sample.txt”)
>>>file = open(“sample.txt”,‟w‟) # Write Mode
# Read and write files in binary mode
>>>file = open(“sam.bmp”,‟rb+‟)
Writing to a file:
fileObject.write(str);
Here, str is the content to be written in opened file
Example:
file=open(“sample.txt”, “w”)
file.write(“Information Technology\n”)
file.write(“Velammal College of Engg and Tech \n\n”)
file.write(“Madurai\n”)
47
Reading Data from a file:
fileObject.read([size])
Here, size is the optional numeric argument and returns a quantity of data
equal to size.
Example:
>>>file = open(“sample.txt”, „r‟, encoding=‟utf-8‟)
>>>file.read(5) # Read the first 5 data
„Infor‟
>>>file.read(6) # Read the next 6 data
„mation‟
fileObject.readline([size])
Here, size is the optional numeric argument and returns a quantity of data
equal to size.
Example:
>>>file.readline( )
„Information Technology‟
>>>file.readline( )
„Velammal College of Engg and Tech\n\n‟
>>>file.readline( )
„Madurai\n‟
>>>file.readline( )
„„
fileObject.readlines([size])
Here, size is the optional numeric argument and returns a quantity of data
equal to size.
Example:
>>>file.readlines( )
[„Information Technology\n‟,‟Velmmal College of Engg and
Tech\n\n‟,‟Madurai\‟]
Closing a file:
fileObject.close( )
Example:
p=open(“sample.txt”,”wb”) # Open a file for writing in binary format
print(“Name of file: “, p.name)
p.close( )
print(“File closed”)
Output:
Name of file: sample.txt
File closed
48
SCRIPT
9.1 Copy from one file to another
INPUT FILE
OUTPUT
49
OUTPUT
50
OUTPUT
51
Ex. No 10. Implementing real-time/technical applications using Exception handling
Aim
The aim of this exercise is to write python script for implementing the given programs
(scripts) using exception handling and execute the same in Python IDLE (through Script or
Development Mode).
Problems Given
Concepts Involved
Exception:
An exception is an irregular state that is originated by a runtime error in the
program.
Python presents two extremely essential features to handle any unpredictable error
in the Python programs and to insert debugging abilities in them.
Exception Handling (Standard Exceptions)
Assertions
An exception is an object that stands for an error. If the exception object is not
fixed and handled appropriately, the interpreter will show an error message.
Error sourced by not following the appropriate syntax of the language is known as
syntax error or parsing error.
Example:
>>>if a<b
Output:
SyntaxError: invalid syntax
The errors that occur during the runtime are called exceptions.
Runtime errors can take place, for example, a file does not present while the
program attempt to open it (FileNotFoundError), function receiving a parameter
that has a right data type but having inappropriate value (ValueError), a module
does not available when the program strive to open it (ImportError) etc.,
When these kinds of runtime error take place, Python produces an exception
object. If the errors are not handled appropriately, it prints a trace back to that
error with several particulars regarding why that error happened.
52
SCRIPT
10.1 Divide by zero error
OUTPUT
OUTPUT
53
10.3 Student mark range validation
OUTPUT
54
Ex. No 11. Exploring Pygame tool
Aim
The aim of this exercise is to write python script for implementing the given programs
(scripts) using exception handling and execute the same in Python IDLE (through Script or
Development Mode).
Concepts Involved
Pygame:
Pygame is a set of Python modules designed to make games. It uses SDL (Simple
DirectMedia Layer) 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.
PyGame in a python library to develop games.
Before starting with pygame we have to install pygame and we must have some programming
knowledge (Python Preferred).
pip install is simplest way
As we know, to play any game we first need a window. So we will first create a window
in the PyGame.
55
Functionality of Code:
o First we imported Pygame library
o Initializing all modules of pygame (pygame.init())
o pygame.display.set_caption , used to display name of the window.
o After that we have created a window. (pygame.display.set_mode(), is a function
in pygame to create window)
o The loop that is placed to stop our windows on the screen.(If we do not loop, our
window will be created but will not stop)
o Inside the event, we handle all the actions that occur above the window.
o Like here we have given the message that if we quit the window (event.type ==
pygame.QUIT) means we close the window, then done become true means our
window is closed.
o pygame.display.flip(),It allows only a portion of the screen to updated, instead of
the entire area.
56
The following code - loading image using pygame:
Functionality of Code:
o What's new for us here,that is pygame.image.load() function, which is used here
to load the image.
o And next is window.blit(),This function says take the image and draw it onto the
window and position it at (x,y).
o As you can see from the output, our image is larger than our window size, this
means that we do not need to take the image size smaller than the window size
(window width and window height)
o (x,y) this is our coordinates where we draw the images on the window.
57
Ex. No 12. Developing a game activity using Pygame like bouncing ball, car race and etc.,
Aim
The aim of this exercise is to write python script for implementing and developing the
game activity (scripts) using Pygame and execute the same in Python IDLE (through Script or
Development Mode).
Problems Given
1. Bouncing a ball
2. Car race
Concepts Involved
Pygame:
Python PyGame library is used to create video games. This library includes
several modules for playing sound, drawing graphics, handling mouse inputs, etc. It is
also used to create client-side applications that can be wrapped in standalone
executables.
SCRIPT
12.1 Bouncing a ball
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Bouncing ball")
ball = pygame.image.load("ball.jpg")
ballrect = ball.get_rect()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: 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:
58
speed[1] = -speed[1]
screen.fill(background)
screen.blit(ball, ballrect)
pygame.display.flip()
ball.jpg
OUTPUT
https://github.com/khan4019/car-race-python-game/blob/master/game.py
59
REFERENCES:
https://realpython.com/tutorials/tools/ - Tools
https://www.upgrad.com/blog/python-developer-
tools/#:~:text=Selenium%20is%20undoubtedly%20one%20of,%2C%20Perl
https://www.mygreatlearning.com/blog/python-tutorial-for-beginners-a-
complete-guide/ - Python
https://www.geeksforgeeks.org/python-programming-language/learn-
python-tutorial/ - Python
https://www.pygame.org/wiki/tutorials - PyGame
https://pythonprogramming.net/pygame-python-3-part-1-intro/ - PyGame
https://www.digitalocean.com/community/tutorials/how-to-install-pygame-
and-create-a-template-for-developing-games-in-python-3 - PyGame
60