Python Program Lab Mannual 1
Python Program Lab Mannual 1
LAB MANUAL
(Regulation 2021)
Prepared by,
1. R.GANESHMURTHI AP/CSE
LIST OF EXPERIMENTS:
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:
SYLLABUS
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.
TOTAL: 60 PERIODS
COURSE OUTCOMES:
1. Allen B. Downey, “Think Python : How to Think like a Computer Scientist”, 2nd Edition, O’Reilly
Publishers, 2016.
2. Karl Beecher, “Computational Thinking: A Beginner’s Guide to Problem Solving and
Programming”, 1st Edition, BCS Learning & Development Limited, 2017.
REFERENCES:
1. Paul Deitel and Harvey Deitel, “Python for Programmers”, Pearson Education, 1st Edition, 2021.
2. G Venkatesh and Madhavan Mukund, “Computational Thinking: A Primer for Programmers and
Data Scientists”, 1st Edition, Notion Press, 2021.
3. John V Guttag, “Introduction to Computation and Programming Using Python: With Applications
to Computational Modeling and Understanding Data‘‘, Third Edition, MIT Press, 2021
4. Eric Matthes, “Python Crash Course, A Hands – on Project Based Introduction to Programming”,
2nd Edition, No Starch Press, 2019.
5. https://www.python.org/
6. Martin C. Brown, “Python: The Complete Reference”, 4th Edition, Mc-Graw Hill, 2018.
EXPT.NO.1 Identification and solving of simple real life or scientific or technical problems,
DATE: and developing flow charts for the same
a) Electricity Billing
Aim:
To Develop a flow chart and write the program for Electricity billing
Procedure:
From Unit To Unit Rate (Rs.) Prices
Flow-Chart:
1c) Sin series
Flow Chart:
1d) To compute Electrical Current in Three Phase AC Circuit
Result :
Thus the flowchart of electric bill ,sine series was successfully verified
EXPT.NO 2.a
DATE: Python Programming Using Simple Statements And Expressions -
Exchange The Values Of Two Variables)
AIM:
Write a python program to exchange the values of two variables
PROCEDURE:
a=10
b=20
a,b=b,a
print("The swapping of a value is=",a)
print("The swapping of b value is=",b)
OUTPUT:
The swapping of a value is= 20
The swapping of b value is= 10
RESULT:
Thus the swapping of two numbers python program was executed successfully and verified.
EXPT.NO.2b Python Programming Using Simple Statements And Expressions - Circulate The
DATE: Values Of N Variables
AIM:
Write a python program to circulate the values of n variables
PROCEDURE:
list1 = []
list1.append(ele)
ele = list1.pop(0)
list1.append(ele)
print(list1)
OUTPUT:
Enter number of values : 4
Enter integer : 87
Enter integer : 58
Enter integer : 98
Enter integer : 52
Circulating the elements of list [87, 58, 98, 52]
[58, 98, 52, 87]
[98, 52, 87, 58]
[52, 87, 58, 98]
[87, 58, 98, 52]
RESULT:
Thus the python program to circulate the values of n variables was executed successfully and verified
XPT.NO.2.C
Python Programming Using Simple Statements And
DATE: Expressions ( Calculate The Distance Between Two
Points)
AIM:
PROCEDURE:
OUTPUT:
enter the value of x1=34
enter the value of x2=56
enter the value of y1=34
enter the value of y2=54
29.732137494637012
RESULT:
Thus the distance between of two points was successfully executed and verified
EXPT.NO.3 (a) Scientific problems using Conditionals and Iterative loops.- Number
DATE: series
AIM:
Write a Python program with conditional and iterative statements for Number Series.
PROCEDURE:
Step 1: Start the program.
Step 2: Read the value of n.
Step 3: Initialize i = 1,x=0.
Step 4: Repeat the following until i is less than or equal to n.
Step 4.1: x=x*2+1.
Step 4.2: Print x.
Step 4.3: Increment the value of i .
Step 5: Stop the program.
PROGRAM:
OUTPUT:
enter the number of terms for the series 5
1
3
7
15
31
RESULT:
Thus the python program to print numbers patterns is executed and verified
EXPT.NO.3B Scientific Problems Using Conditionals And Iterative Loops. –Number
Patterns
DATE:
AIM:
Write a Python program with conditional and iterative statements for Number Pattern.
PROCEDURE:
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 i
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
rows = int(input('Enter the number of rows'))
for i in range(rows+1):
for j in range(i):
print(i, end=' ')
print(' ')
OUTPUT:
RESULT:
Thus the python program to print numbers patterns is executed and verified
EXPT.NO.3 c
DATE: Scientific Problems Using Conditionals And Iterative Loops. -Pyramid
AIM:
Write a Python program with conditional and iterative statements for Pyramid Pattern.
PROCEDURE:
def pypart(n):
for i in range(0, n):
for j in range(0, i+1):
print(“*”,end=” “)
print(“\r”)
O/P:
enter the no. of rows 5
*
**
***
****
*****
RESULT:
Thus the python program to print numbers pyramid patterns is executed and verified.
EXPT.NO.4(a)
DATE: Implementing Real-Time/Technical Applications Using Lists, Tuples
-Items Present InA Library)
AIM :
To Write a python program to implement items present in a library
PROCEDURE:
STEP 1: Start the program
STEP 2: Create the variable inside that variable assigned the list of elements based on the library
using List and tuple
STEP 3:Using array index to print the items using list and tupel
STEP 4:To print the result using output statement
STEP 5: Stop the program
PROGRAM:
TUPLE:
tup1 = (12134,250000 )
tup2 = ('books', 'totalprice')
# tup1[0] = 100 ----------Not assigned in tuple # So let's create a new tuple as follows
tup3 = tup1 + tup2;
print(tup3)
OUTPUT:
ramayanam
['ramayanam', 'valmiki', 123987, 234]
TUPLE:
(12134, 250000, 'books', 'totalprice')
RESULT:
Thus the Python Program is executed successfully and the output is
Verified.
EXPT.NO.4 b Implementing Real-Time/Technical Applications Using Lists, Tuples -Components
DATE: Of a Car
AIM:
To Write a python program to implement components of a car
PROCEDURE:
STEP 2: Create the variable inside that variable assigned the list of elements based on the car
STEP 3:Using array index to print the items using list and tuple
OUTPUT:
LIST:
TUPLE:
Ferrari
BMW
Jaguar
Jaguar
RESULT:
Thus the Python Program is executed successfully and the output is verified.
EXPT.NO.4 C Implementing Real-Time/Technical Applications Using Lists, Tuples - Materials Required
DATE: For Construction Of A Building.
AIM:
To Write a python program to implement materials required for construction of building
PROCEDURE:
OUTPUT:
LIST:
['cementbags', 'bricks', 'Aggregates', 'Steelbars', 'Paint', 'electrical']
TUPLE:
('cementbags', 'bricks', 'sand', 'Steelbars', 'Paint')
list of element is= ('cementbags', 'bricks', 'sand', 'Steelbars', 'Paint')
materials[0]: cementbags
materials[1:3]: ('bricks', 'sand')
RESULT:
Thus the Python Program is executed successfully and the output is verified.
EXPT.NO: 5 Implementing Real-Time/Technical Applications Using Sets, Dictionaries. –
DATE: Components Of An Automobile
AIM:
To write a python program to implement Components of an automobile using
Sets and Dictionaries
PROCEDURE:
OUTPUT:
Empty Dictionary:
{}
Dictionary after adding 3 elements: {0: 'BRICKS', 2: 'CEMENT', 3: 'BLUE_PRINT', 'Value_set': (2, 3, 4)}
PROCEDURE:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
n=int(input("Input a number
to compute the factiorial : "))
print(factorial(n))
OUTPUT:
RESULT:
Thus the program was executed and verified successfully
EXPT.NO 6 B Implementing Program Largest Number In A List Using Function
DATE:
AIM:
To Write a Python program to get the largest number from a list.
PROCEDURE:
OUTPUT:
2
RESULT:
Thus the program was executed and verified successfully
EXPT.NO.6 (C) Implementing Programs Using Functions – Area Of Shape
DATE
AIM:
To Write a python program to implement area of shape using functions
PROCEDURE:
Step 1:Get the input from the user shape’s name.
Step 2:If it exists in our program then we will proceed to find the entered shape’s area according to
their respective formulas.
Step 3:If that shape doesn’t exist then we will print “Sorry!
Step 4: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(f"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(f"The area of triangle is{circ_area}.")
elif name == 'parallelogram':
b = int(input("Enter parallelogram's base length: "))
h = int(input("Enter parallelogram's height length: "))
# calculate area of parallelogram
para_area = b * h
print(f"The area of parallelogram is{para_area}.")
else:
print("Sorry! This shape is not available")
if __name == " main " :
print("Calculate Shape Area")
shape_name = input("Enter the name of shape whose area you want to find: ")
calculate_area(shape_name)
OUTPUT:
RESULT:
Thus the python program to implement area of shape using functions was successfully
executed and verified
EXPT.NO.7 (A) Implementing programs using Strings –Reverse
DATE
AIM:
PROCEDURE:
def reverse(string):
string = string[::-1]
return string
s = "Firstyearece"
print ("The original string is : ",end="")
print (s)
print ("The reversed string(using extended slice syntax) is : ",end="")
print (reverse(s))
OUTPUT:
RESULT:
Thus the reverse of a string function python program was executed and successfully
verified
EXPT.NO.7 (B)
DATE: Implementing Programs Using Strings -Palindrome
AIM:
PROCEDURE:
Step 1: start by declaring the isPalindrome() function and passing the string
argument.
Step 2:Then, in the function body,
Step 3:To get the reverse of the input string using a slice operator – string[::-1].
Step 4: -1 is the step parameter that ensures that the slicing will start from the
end of the string with one step back each time.
Step 5:if the reversed string matches the input string, it is a
palindrome Or else, it is not a palindrome.
PROGRAM:
def is Palindrome(s):
return s == s[::-1]
# Driver code
ans = isPalindrome(s)
if ans:
OUTPUT:
Enter a string:madam
The string is a palindrome
RESULT:
Thus the program of palindrome by using function in python executed successfully and verified
EXPT.NO: 7 (C)
DATE: Implementing programs using Strings - character count
AIM:
PROCEDURE:
Step 1: user to enter the string. Read and store it in a variable.
Step 2: Initialize one counter variable and assign zero as its value.
Step 3: increment this value by 1 if any character is found in the string.
Step 4: Using one loop, iterate through the characters of the string one by one.
Step 5: Check each character if it is a blank character or not. If it is not a blank
character, increment the value of the counter variable by ’1‘.
Step 6: After the iteration is completed, print out the value of the counter.
Step 7: This variable will hold the total number of characters in the string.
PROGRAM:
OUTPUT:
RESULT:
Thus the program of character count in string in python was executed successfully and verified
EXPT.NO: 7 (d)
DATE: Implementing programs using Strings – Replacing
Characters
AIM:
PROCEDURE:
OUTPUT:
RESULT:
Thus the program was executed and successfully verified
EXPT.NO: 8 (a)
DATE: Implementing programs using written modules and
Python Standard Libraries–pandas
AIM:
To write a python program to implement pandas modules. Pandas are
denote python data structures.
PROCEDURE:
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:
RESULT:
AIM:
To Write a python program to implement numpy module in python .
Numerical python are mathematical calculations are solved here.
PROCEDURE:
import numpy as np
a = np.arange(6)
a2 = a[np.newaxis, :]
a2.shape
#Array Creation and functions:
a = np.array([1, 2, 3, 4, 5, 6])
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(a[0])
print(a[1])
np.zeros(2)
np.ones(2)
np.arange(4)
np.arange(2, 9, 2)
np.linspace(0, 10, num=5)
x = np.ones(2, dtype=np.int64)
print(x)
arr = np.array([2, 1, 5, 3, 7, 4, 6, 8])
np.sort(arr)
a = np.array([1, 2, 3, 4])
b = np.array([5, 6, 7, 8])
np.concatenate((a, b))
#Array Dimensions:
array_example = np.array([[[0, 1, 2, 3], [4, 5, 6, 7]], [[0, 1, 2, 3], [4, 5, 6, 7]],
[[0 ,1 ,2, 3], [4, 5, 6, 7]]])
array_example.ndim
array_example.size
array_example.shape
a = np.arange(6)
print(a)
b=a.reshape(3, 2)
print(b)
np.reshape(a, newshape=(1, 6), order='C')
OUTPUT:
[1 2 3 4]
[5 6 7 8]
[1 1]
[0 1 2 3 4 5]
[[0 1]
[2 3]
[4 5]]
RESULT:
AIM:
To write a python program to implement matplotolib module in python. .Matplotlib
python are used to show the visualization entities in python.
PROCEDURE:
PROGRAM 2:
RESULT:
Thus the python program to implement matplotolib module in python.
Matplotlib python are used to show the visualization entites in python was
successfully executed and verified.
EXPT.NO: 8 (d)
DATE: Implementing programs using written modules and Python Standard
Libraries– scipy
AIM:
Write a python program to implement scipy module in python. .Scipy python
are used to solve the scientific calculations
PROCEDURE:
Step 3:To import the package of np in a program and create x,x1,y,y1 identifier
Step 4: SciPy provides interp1d function that can be utilized to produce univariate
interpolation
RESULT:
Thus the python program to implement Scipy module in python.
Scipy python are used to show the visualization entites in python was
successfully executed and verified.
EXPT.NO: 9 (a)
DATE: Implementing real-time/technical applications using File handling -
copy from one file to another
AIM:
To Write a python program to implement File Copying
PROCEDURE:
AIM:
PROCEDURE:
Step 1: Open and create the txt file with some statements
step 2: To save that file with the extension of txt file
step3 : Now to count the the lenghth of word in a file.
step 4: To display the word count in a target file
PROGRAM:
file =open(r"C:\Users\Administrator\Desktop\count2.txt","rt")
data = file.read()
words = data.split()
print('Number of words in text file :', len(words))
OUTPUT:
Number of words in text file : 4
RESULT:
Thus the python program to implement word count in File operations in python was
executed successfully and verified
EXPT.NO: 9 (c)
DATE: Implementing real-time/technical applications using File handling -
Longest word
AIM:
def longest_word(count):
with open(count, 'r') as infile:
words = infile.read().split()
max_len = len(max(words, key=len))
return [word for word in words if len(word) == max_len]
print(longest_word('count.txt'))
OUTPUT:
['welcome', 'program']
RESULT:
Thus the python program to implement longest word in File operations was executed
successfully verified.
EXPT.NO: 10 (a)
DATE: Implementing real-time/technical applications using Exception
handling.- divide by zero error.
AIM:
To Write a exception handling program using python to depict the divide by zero
error.
PROCEDURE:
program
a=int(input("Entre a="))
b=int(input("Entre b="))
try:
c = ((a+b) / (a-b))
#Raising Error
if a==b:
raise ZeroDivisionError
#Handling of error
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)
OUTPUT:
Entre a=4
Entre b=6
-5.0
RESULT:
Thus the exception handling program using python to depict the divide by zero
error. was successfully executed and verified
EXPT.NO: 10 (b)
DATE: Implementing real-time/technical applications using Exception
handling.- Check voters eligibility
AIM:
To Write a exception handling program using python to depict the voters eligibility
PROCEDURE:
Step 1: Start the program
Step 2:Read the input file which contains names and age by using try catch exception handling
method
Step 3:To Check the age of the person. if the age is greater than 18 then write the name into voter
list otherwise write the name into non voter list.
Step 4: Stop the program
program:
def main():
#get the age
try:
age=int(input("Enter your age"))
if age>18:
print("Eligible to vote")
else:
print("Not eligible to vote")
except:
print("age must be a valid number")
main()
OUTPUT:
Enter your age43
Eligible to vote
RESULT:
Thus the exception handling program using python to depict the voters eligibility
was successfully executed and verified.
EXPT.NO: 10 (c)
DATE: Implementing real-time/technical applications using Exception
handling.- student mark range validation
AIM:
To Implementing real-time/technical applications using Exception handling.- student mark
range validation
PROCEDURE:
Step 1: Start the program
Step 2:By using function to get the input from the user
Step 3:Using Exception handling in that cif statement can be used to check the mark range in the
program
Step 4:Given data is not valid it will throw the IOexception in the process
Step 5: Stop the program
PROGRAM:
def main():
try:
mark=int(input(“enter your mark”))
if mark>=35 and mark<101:
print(“pass and your mark is valid”)
else:
print(“fail and your mark is valid”)
except ValueError:
print(“mark must be avalid number”)
except IOError:
print(“enter correct valid mark”)
except:
print(“An error occurred”)
main()
OUTPUT:
Enter your mark 69
Pass and your mark is valid
RESULT:
Thus the real-time/technical applications using Exception handling.- student mark
range validation was successfully executed and verified
EXPT.NO: 11
DATE: Exploring Pygame tool.
AIM:
To Write a python program to implement pygame
PROCEDURE:
step 1: start the program
step 2: when Key presses, mouse movements, and even joystick movements are some
of the ways in which a user can provide input
step 3: To sets up a control variable for the game loop. To exit the loop and the game,
you set running = False. The game loop starts on line 29.
step 4: starts the event handler, walking through every event currently in the event
queue. If there are no events, then the list is empty, and the handler won’t do anything.
step 5:check if the current event.type is a KEYDOWN event. If it is, then the program
checks which key was pressed by looking at the event.key attribute. If the key is the
Esc key, indicated by K_ESCAPE, then it exits the game loop by setting running =
False.
step 6: do a similar check for the event type called QUIT. This event only occurs when
the user clicks the window close button. The user may also use any other operating
system action to close the window.
step 7:The window won’t disappear until you press the Esc key, or otherwise trigger
a QUIT event by closing the window.
PROGRAM:
import pygame
from pygame.locals import *
class Square(pygame.sprite.Sprite):
def init (self):
super(Square, self). init ()
self.surf = pygame.Surface((25, 25))
self.surf.fill((0, 200, 255))
self.rect = self.surf.get_rect()
pygame.init()
screen = pygame.display.set_mode((800, 600))
square1 = Square()
square2 = Square()
square3 = Square()
square4 = Square()
gameOn = True
while gameOn:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_BACKSPACE:
gameOn = False
elif event.type == QUIT:
gameOn = False
screen.blit(square1.surf, (40, 40))
screen.blit(square2.surf, (40, 530))
screen.blit(square3.surf, (730, 40))
screen.blit(square4.surf, (730, 530))
pygame.display.flip()
OUTPUT
RESULT:
Thus the python program to implement pygame was successfully executed and
verified.
EXPT.NO: 12
DATE: Developing a game activity using Pygame like bouncing ball
AIM:
To Write a python program to implement bouncing balls using pygame tool
PROCEDURE:
Step1: Start the program
Step 2:The pygame.display.set_mode() function returns the surface object for the window.
This function accepts the width and height of the screen as arguments.
Step 3:To set the caption of the window, call the pygame.display.set_caption() function.
opened the image using the pygame.image.load() method and set the ball rectangle area boundary
using
the get_rect() method.
Step 4:The fill() method is used to fill the surface with a background color.
Step 5:pygame flip() method to make all images visible.
Step 6: Stop the program
PROGRAM:
import sys, pygame
pygame.init()
size = width, height = 800, 400
speed = [1, 1]
background = 255, 255, 255
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Bouncing ball")
ball = pygame.image.load("ball.png")
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:
speed[1] = -speed[1]
screen.fill(background)
screen.blit(ball, ballrect)
pygame.display.flip()
OUTPUT:
RESULT:
Thus the python program to implement bouncing balls using pygame tool was
executed successfully and verified
ALL THE BEST …!