0% found this document useful (0 votes)
6 views21 pages

Python Lab Manual

The document is a practical laboratory report for a Python programming course at Jeppiaar University, detailing various programming experiments conducted during the academic year 2022-2023. It includes aims, algorithms, programs, outputs, and results for tasks such as calculating distances, generating patterns, and using data structures like lists and dictionaries. Each experiment demonstrates the application of Python programming concepts in solving real-world problems.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views21 pages

Python Lab Manual

The document is a practical laboratory report for a Python programming course at Jeppiaar University, detailing various programming experiments conducted during the academic year 2022-2023. It includes aims, algorithms, programs, outputs, and results for tasks such as calculating distances, generating patterns, and using data structures like lists and dictionaries. Each experiment demonstrates the application of Python programming concepts in solving real-world problems.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

BONAFIDE

CERTIFICATE

This is certify that, this a bonafide record work done by

Mr. /Ms……………………………………………………Year………Semester……………

Register No. ………………………………For .......................................................................... Program

in the School of…………………………………………………………………………………

at JEPPIAAR UNIVERSITY, CHENNAI during the academic year 2022-2023.

………………… …………………

Signature Signature

Faculty In-Charge Dean

Submitted for Jeppiaar University Practical Examination Held On ……………….

………………………. ………………………….

Signature Signature

Internal Examiner (With Date) External Examiner (With Date)


INDEX

STAFF
SNO DATE EXPERIMENT MARK
SIGN
Python programming using simple statements and
1
expressions: circulate the values of n variables,
Distance between two points.

Scientific problems using Conditionals and iterative


2 loops: Number pattern, Pyramid pattern.
Implementing real-time technical applications using
3
Lists, Tuples: Materials required for construction of a
building.

Implementing real-time technical applications using


4
Sets, Dictionaries: Components of an automobile.

Implementing programs using functions: Large number


5 in a list, area of shape.
Implementing programs using strings: Reverse,
6
Palindrome.

Implementing programs using written modules and


7
Python Standard Libraries: pandas, numpy, Matplotlib,
scipy.

Implementing real-time technical applications using


8
File handling: Copy from one program to another.

Implementing real-time technical applications using


9
Exception handling: Divide by zero error.
DATE:
[Link] : 1) i) Python programming using simple statements and expressions: Circulate the
values of n variables.

AIM : To write a program to circulate the values of n variables using simple statements and
expressions.

ALGORITHM :

Step 1 : Start the program

Step 2 : Initialize numbers using list.

Step 3 : Also get a value n for rotation.

Step 4 : Obtain the numbers available from the nth position, the numbers till n position

and append the both values.

Step 5: Display the result.

Step 6: Stop the program.

PROGRAM:
# Right Rotating a list to n positions

n= int(input("enter n value : "))

list_1 = [1, 2, 3, 4, 5, 6]

list_2 = (list_1[-n:] + list_1[:-n])

print("Rotating {} by {} position is {}".format(list_1,n,list_2))

OUTPUT:
enter n value : 3
Rotating [1, 2, 3, 4, 5, 6] by 3 position is [4, 5, 6, 1, 2, 3]

RESULT:
Thus the program using simple statements and expressions is written and executed successfully.

1 ECS42002 – Python Programming Laboratory

[Link] CSE, AIML, DS


DATE:
[Link] : 1) ii) Python programming using simple statements and expressions: Distance between
two points.

AIM : To write a program to find the distance between two points using simple statements and
expressions

ALGORITHM :

Step 1: Start the program.


Step 2: Get two points, namely(x1,y1) and (x2,y2).
Step 3: Calculate the distance between two points by using ( (x2 - x1) 2 + (y2 - y1) 2) ½.
Step 4: Display the resultant distance value.
Step 5: Stop the program

PROGRAM:
#Python program to find distance between two points

# point a

x1 = float(input(“enter x1 : ”))

y1 = float(input(“enter y1 : ”))

# point b

x2 = float(input(“enter x2 : ”))

y2 = float(input(“enter y2 : ”))

# distance between a and b

distance = ((x1 - x2)**2 + (y1 - y2)**2)**0.5

# display the result

print("Distance between points ({}, {}) and ({}, {}) is {}".format(x1,y1,x2,y2,distance))

OUTPUT:
enter x1 : 2
enter y1 : 3
enter x2 : 5
enter y2 : 7
Distance between points (2.0, 3.0) and (5.0, 7.0) is 5.0

RESULT:
Thus the program using simple statements and expressions is written and executed successfully.

2 ECS42002 – Python Programming Laboratory

[Link] CSE, AIML, DS


DATE:
[Link] : 2) i) Scientific problems using Conditionals and iterative loops: Number pattern,

AIM : To write a program to solve Number pattern.

ALGORITHM :
Step 1: Get the X and Y values as input from the user
Step 2: Initialize two variables to store the square and sum
Step 3: Initialize i=1
Step 4: Repeat Step 5 through Step 12 until i <= X*2+Y
Step 5: if X-i >= 0 goto Step 6 else goto Step 8
Step 6: Calculate a = X-i
Step 7 : Display a
Step 8: if X-i < 0 goto Step 9 else goto Step 12
Step 9: Calculate a = X-i
Step 10: Calculate a = a + a*-2
Step 11: Display a
Step 12: Increment i by 1
Step 13: Stop

PROGRAM:
X = int(input("Please enter the value of X:"))
Y = int(input("Please enter the value of Y:"))
print('The Series for',X,'and',Y,'is:',end=' ' )
for i in range(0,X*2+Y,Y):
if X-i >= 0:
a = X-i
print(a,end=' ')
elif X-i < 0:
a = X-i
a = a + a*-2
print(a,end=' ')

OUTPUT:
Please enter the value of X:14
Please enter the value of Y:3
The Series for 14 and 3 is: 14 11 8 5 2 1 4 7 10 13 16

RESULT:
Thus the program using Conditionals and iterative loops is written and executed successfully.

3 ECS42002 – Python Programming Laboratory

[Link] CSE, AIML, DS


DATE:
[Link] : 2) ii) Scientific problems using Conditionals and iterative loops: Pyramid pattern.

AIM : To write a program to solve Pyramid pattern.

ALGORITHM :
Step 1: Get the number of rows R from the user
Step 2: Initialize a temporary variable K to count on number of spaces
Step 3: Initialize i=1. Create an outer loop to handle number of rows.
Step 4: Repeat Step 5 through Step 8 until i <=n
Step 5: Initialize j=1. Create inner loop to handle number spaces.
Step 6: Repeat Step 7 through Step 8 until j <=n
Step 7: Display a space
Step 8: Decrement K by 1 after each loop
Step 9: Initialize j=1. Create inner loop to handle number of columns.
Step 10: Repeat Step 11 through Step 13 until j <=n
Step 11: Display ‘*’
Step 12: Increment i
Step 13: Stop

PROGRAM:
n = int(input("Please enter the value of N:"))
k=n-1
for i in range(0, n):
for j in range(0, k):
print(end=" ")
k=k-1
for j in range(0, i+1):
print("* ", end="")
print("\r")

OUTPUT:
Please the Number of rows R:03
*
**
***

RESULT:
Thus the program using Conditionals and iterative loops is written and executed successfully.

4 ECS42002 – Python Programming Laboratory

[Link] CSE, AIML, DS


DATE:
[Link] : 3) Implementing real-time/technical applications using Lists, Tuples: Materials
required for construction of a building.

AIM : To write a program to implementing real-time/technical applications using Lists, Tuples:


Materials required for construction of a building.

ALGORITHM :
Step 1: Print the actual string
Step 2: Slice and print the substring from the string
Step 3: Get the common materials required for construction as input from the user as List
Step 4: Store the inputs in a List
Step 5: Perform slicing operations in the list
Step 6: Get the common materials required for construction as input from the user as Tuple
Step 7: Store the inputs in a Tuple
Step 8: Perform slicing operations in the Tuple
Step 9: Stop

PROGRAM:
str_x = "Common Materials required for construction"
print("Actual string: ", str_x)
obj_slice = slice(7, 25)
print("The substring after slice (7, 25):" ,str_x[obj_slice])
MaterialList = list(map(str, input("Enter the Material List required for
construction separated by space: ").split()))
print("Original List:", MaterialList)
obj_slice = slice(1, 5, 1)
print("Sliced List with slice(1, 5, 1):", MaterialList[obj_slice])
obj_slice = slice(-1,-4, -1)
print("The List after negative values for slice:" ,MaterialList[obj_slice])
print("Sliced List with [2:6:1:", MaterialList[2:6:1])
print("Sliced List with [1::]:", MaterialList[1::])
MaterialTuple = list(map(str, input("Enter the Material Tuple required for
construction separated by space: ").split()))
print("Original Tuple:", MaterialTuple)
obj_slice = slice(4)
print("The tuple after slice:" ,MaterialTuple[obj_slice])
print("Sliced Tuple with [:]:", MaterialTuple[:])
print("Sliced Tuple with [::-1] = ", MaterialTuple[::-1])
print("Sliced Tuple with [-1:-4:-1] = ", MaterialTuple[-1:-4:-1])

5 ECS42002 – Python Programming Laboratory

[Link] CSE, AIML, DS


OUTPUT:
Actual string: Common Materials required for construction
The substring after slice (7, 25): Materials required
Enter the Material List required for construction separated by space: Sand Steel Stones PVC
Plaster Putty
Original List: ['Sand', 'Steel', 'Stones', 'PVC', 'Plaster', 'Putty']
Sliced List with slice(1, 5, 1): ['Steel', 'Stones', 'PVC', 'Plaster']
The List after negative values for slice: ['Putty', 'Plaster', 'PVC']
Sliced List with [2:6:1: ['Stones', 'PVC', 'Plaster', 'Putty']
Sliced List with [1::]: ['Steel', 'Stones', 'PVC', 'Plaster', 'Putty']
Enter the Material Tuple required for construction separated by space: Cement Sand Bars Bricks
Paint Wood Tiles
Original Tuple: ['Cement', 'Sand', 'Bars', 'Bricks', 'Paint', 'Wood', 'Tiles']
The tuple after slice: ['Cement', 'Sand', 'Bars', 'Bricks']
Sliced Tuple with [:]: ['Cement', 'Sand', 'Bars', 'Bricks', 'Paint', 'Wood', 'Tiles']
Sliced Tuple with [::-1] = ['Tiles', 'Wood', 'Paint', 'Bricks', 'Bars', 'Sand', 'Cement']
Sliced Tuple with [-1:-4:-1] = ['Tiles', 'Wood', 'Paint']

RESULT:
Thus the program to implement real-time/technical applications using Lists, Tuples is written
and executed successfully.

6 ECS42002 – Python Programming Laboratory

[Link] CSE, AIML, DS


DATE:
[Link] : 4) Implementing real-time/technical applications using Sets, Dictionaries: Components
of an automobile.

AIM : To write a program to implementing real-time/technical applications using Sets,


Dictionaries: Components of an automobile.

ALGORITHM :
Step 1: Create an automobile component dictionary pair, key: value as {Type: Bike,
Engine: 2Stroke, Capacity: 100cc}
Step 2: Access the value for the Key "Engine"
Step 3: Access the value for the Key "Engine" using get
Step 4: Add a new key: value as Cost: 75000
Step 5: Update the pair for the key "Engine" as "4Stroke"
Step 6: Remove the particular "Cost" key using pop
Step 7: Remove an arbitrary key using popitem
Step 8: Delete the particular "Engine" key
Step 9: Clear the dictionary
Step 10: Delete the dictionary
Step 11: Display the error on printing deleted dictionary
Step 12: Stop
PROGRAM:
#Step 1
v1=input("Enter input pair for Key 'Chasis' : ")
v2=input("Enter input pair for Key 'Engine' : ")
v3=input("Enter input pair for Key 'Capacity' : ")
v4=input("Enter input pair for Key 'Variant' : ")
automobile={"Chasis":v1, "Engine":v2, "Capacity":v3, "Variant":v4}
print(automobile)
#Step 2
x = automobile["Engine"]
print(x)
#Step 3
x = [Link]("Engine")
print(x)
#Step 4
automobile['Cost'] = '75000'
print(automobile)
#Step 5
automobile['Engine'] = "TwinCylinder"
print(automobile)

7 ECS42002 – Python Programming Laboratory

[Link] CSE, AIML, DS


#Step 6
print([Link]("Cost"))
print(automobile)
#Step 7
print([Link]())
print(automobile)
#Step 8
del automobile["Engine"]
print(automobile)
#Step 9
[Link]()
print(automobile)
#Step 10
del automobile
#Step 11
print(automobile)
OUTPUT:
Enter input pair for Key 'Chasis' : Hatchback
Enter input pair for Key 'Engine' : VCylinder
Enter input pair for Key 'Capacity' : 1000cc
Enter input pair for Key 'Variant' : Petrol
{'Chasis': 'Hatchback', 'Engine': 'VCylinder', 'Capacity': '1000cc', 'Variant': 'Petrol'}
VCylinder
VCylinder
{'Chasis': 'Hatchback', 'Engine': 'VCylinder', 'Capacity': '1000cc', 'Variant': 'Petrol', 'Cost': '75000'}
{'Chasis': 'Hatchback', 'Engine': 'TwinCylinder', 'Capacity': '1000cc', 'Variant': 'Petrol', 'Cost':
'75000'}
75000
{'Chasis': 'Hatchback', 'Engine': 'TwinCylinder', 'Capacity': '1000cc', 'Variant': 'Petrol'}
('Variant', 'Petrol')
{'Chasis': 'Hatchback', 'Engine': 'TwinCylinder', 'Capacity': '1000cc'}
{'Chasis': 'Hatchback', 'Capacity': '1000cc'}
{}
Traceback (most recent call last):
File "<string>", line 35, in <module>
NameError: name 'automobile' is not defined

RESULT:
Thus the program to implement real-time/technical applications using Sets, Dictionaries is
written and executed successfully.

8 ECS42002 – Python Programming Laboratory

[Link] CSE, AIML, DS


DATE:
[Link] : 5) i) Implementing programs using functions: Large number in a list.

AIM : To implementing programs using functions: Large number in a list.

ALGORITHM :
Step 1: Start
Step 2: Create an empty list
Step 3: Read list elements from User
Step 4: Assign first number in list to variable "max"
Step 5: Use for loop compare each number with "max" value
Step 6: Assign the largest value to "max'
Step 7: Repeat Step 5 and 6 until reach the last element of the list
Step 8: Print max as largest number in the list

PROGRAM:
# Python program to find largest number in a list

# creating empty list

list1 = []

# asking number of elements to put in list

num = int(input("Enter number of elements in list: "))

# iterating till num to append elements in list

for i in range(1, num + 1):

ele = int(input("Enter elements: "))

[Link](ele)

# print maximum element

print("Largest element is:", max(list1))

OUTPUT:
Enter the list of elements:[5,8,3 9,2]
The largest number in the list is 9

RESULT:
Thus the program to implement programs using functions is written and executed successfully.

9 ECS42002 – Python Programming Laboratory

[Link] CSE, AIML, DS


DATE:
[Link] : 5) ii) Implementing programs using functions: Area of shape.

AIM : To implementing programs using functions: Area of shape

ALGORITHM :
Step 1: Select the shape

Step 2: If it is rectangle do the following

Step 2.1: Enter the width of the rectangle.

Step 2.2: Enter the Height of the rectangle.

Step 2.3: Calculate the area of the rectangle by multiplying the width and height of the rectangle.

Step 2.4: Assign the area of the rectangle to the area variable.

Step 2.5: print the area of the rectangle.

Step 3: If it is triangle do the following

Step 3.1: Enter the breadth of the triangle

Step 3.2: Enter the Height of the triangle

Step 3.3: Calculate the area of the rectangle by multiplying the breadth and height of the triangle

Step 3.4: Assign the area of the triangle to the area variable.

Step 3.5: print the area of the triangle

Step 4: If it is square do the following

Step 4.1: Enter the side of the square

Step 4.2: Calculate the area of the square by multiplying the 4 sides

Step 4.3: Assign the area of the Square to the area variable.

Step 4.4: Print the area of the square

Step 5: If it is circle do the following

Step 5.1: Enter the radius of the circle

Step 5.2: Calculate the area of the circle by 𝐴 = 𝜋𝑟2

Step 5.3: Assign the area of the circle to the area variable.

Step 5.4: Print the area of the circle

10 ECS42002 – Python Programming Laboratory

[Link] CSE, AIML, DS


PROGRAM:
# define a function for calculating the area of a shapes

def calculate_area(name):

# converting all characters into lower cases

name = [Link]()

# check for the conditions

if name == "rectangle":

l = int(input("Enter rectangle's length: "))

b = int(input("Enter rectangle's breadth: "))

# calculate area of rectangle

rect_area = l * b

print(f"Area of rectangle is {rect_area}.")

elif name == "square":

s = int(input("Enter square's side length: "))

# calculate area of square

sqt_area = s * s

print(f"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: "))

# calculate area of triangle

tri_area = 0.5 * b * h

print(f"Area of triangle is

{tri_area}.")

elif name == "circle":

r = int(input("Enter circle's radius length: "))

11 ECS42002 – Python Programming Laboratory

[Link] CSE, AIML, DS


pi = 3.14

# calculate area of circle

circ_area = pi * r * r

print(f"The area of triangle is

{circ_area}.")

else:

print("Sorry! This shape is not available")

# driver code

if __name__ == "__main__" :

print("Calculate Shape Area")

shape_name = input("Enter the name of shape whose area you want to find: ")

# function calling

calculate_area(shape_name)

OUTPUT:
Enter name of the shape: Rectangle
Enter rectangle's length: 4
Enter rectangle's breadth:3
Area of Rectangle:12
Enter name of the shape: Triangle
Enter triangle's height length: 4
Enter triangle's breadth length: 3
Area of Triangle: 6
Enter name of the shape: Square
Enter square's side length: 4
Area of Square: 16
Enter name of the shape: Circle
Enter circle's radius length: 4
Area of Circle: 50.24
Enter rectangle's length: s could not convert string to float: 's'

RESULT:
Thus the program to implement programs using functions is written and executed successfully.

12 ECS42002 – Python Programming Laboratory

[Link] CSE, AIML, DS


DATE:
[Link] : 6) i) Implementing programs using strings: Reverse.

AIM : To write a program to implement reverse operation in strings.

ALGORITHM :
Step 1: Get the input from the user and store the value in a
Step 2: Use slice statement and read the string
.Step 3: Print the reverse String

PROGRAM:
a=input("please enter the string a:")
x=a[::-1]
print("Reverse string is:",x)

OUTPUT:
Please enter the string a:welcome
Reverse string is:
Emoclew

RESULT:
Thus the program to implement programs using strings is written and executed successfully.

13 ECS42002 – Python Programming Laboratory

[Link] CSE, AIML, DS


DATE:
[Link] : 6) ii) Implementing programs using strings: Palindrome.

AIM : To write a program to check if a string is palindrome or not.

ALGORITHM :
Step 1: Get the input string from user and store in x
Step 2: Define a palindrome function
Step 3: Use slicing function and reverse the string
Step 4: check both the string are same
Step 5: If yes, The string is Palindrome
Step 6: If not, The string is not a Palindrome

PROGRAM:
def isPalindrome(x):
return x == x[::-1]
x = input("Please enter the string x:")
y = isPalindrome(x)
if y:
print("Yes,The string is Palindrome ")
else:
print("No,The string is not a Palindrome")

OUTPUT:
Please enter the string x:malayalam
Yes,The string is Palindrome

RESULT:
Thus the program to implement programs using strings is written and executed successfully.

14 ECS42002 – Python Programming Laboratory

[Link] CSE, AIML, DS


DATE:
[Link] : 7) Implementing programs using written modules and Python Standard Libraries:
pandas, numpy, Matplotlib, scipy.

AIM : To write a program to implement programs using written modules and Python Standard
Libraries: pandas, numpy, Matplotlib, scipy.

ALGORITHM :
Step1: Take a list of 8 Numbers.
Step2: Compute the Mean value by simple Computation and print it.
Step3: Compute the Mean value using numpy method and print it.
Step4: Compute the Median value by simple Computation and print it.
Step5: Compute the Mode value by simple Computation and print it.
Step6: Compute the Mode value using numpy method and print it.
Step7: Compute the IQR (Inter Quartile Range) by simple Computation and print it.
Step8: Compute the Standard Deviation by simple Computation and print it.
Step9: Compute the Standard Deviation using Numpy and print it.
Step 10: Stop

PROGRAM:
import numpy as n
from collections import Counter
from scipy import stats
# Finding Mean by simple Computation
a= [11, 21, 34, 22, 27, 11, 23, 21]
mean = sum(a)/len(a)
print (mean)
# Finding Mean using numpy method
mean = [Link](a)
print (mean)
# Finding Median by simple Computation.
def median(nums):
[Link]()
if len(nums)%2 == 0:
return int(nums[len(nums)//2-1]+nums[len(nums)//2])/2
else:
return nums[len(nums)//2]
print (median(a))
# Finding Mode by simple Computation
data = dict(Counter(a))
mode = [k for k, v in [Link]() if v == max(list([Link]()))]
15 ECS42002 – Python Programming Laboratory

[Link] CSE, AIML, DS


print (mode)
# Finding Mode using numpy method
print ([Link](a)[0][0])
# Finding Quartiles by simple method
def quartiles(nums):
nums=sorted(nums)
Q1 = median(nums[:len(nums)//2])
Q2 = median(nums)
if len(nums)%2 == 0:
Q3 = median(nums[len(nums)//2:])
else:
Q3 = median(nums[len(nums)//2+1:])
return Q1,Q2,Q3
def median(nums):
[Link]()
if len(nums)%2 == 0:
return int(nums[len(nums)//2-1]+nums[len(nums)//2])/2
else:
return nums[len(nums)//2]
print (quartiles(a))
# Find Standard deviation by simple computation
n=len(a)
std=(sum(map(lambda x: (x-sum(a)/n)**2,a))/n )**0.5
print(std)
# Find Standard deviation using numpy method
print ([Link](a))

OUTPUT:
Mean= 21.25
Mean= 21.25
Median 21.5
Mode [11, 21]
Mode 11
Quartiles (16.0, 21.5, 25.0)
Standard Deviation Simple Method: 7.1545440106270926
Standard Deviation using Numpy: 7.1545440106270926

RESULT:
Thus the program to implement programs using written modules and Python Standard Libraries
is written and executed successfully.

16 ECS42002 – Python Programming Laboratory

[Link] CSE, AIML, DS


DATE:
[Link] : 8) Implementing real-time/technical applications using File handling: Copy from one
program to another.

AIM : To write a program to implement real-time/technical applications using File handling:


Copy from one program to another.

ALGORITHM :
Step1: Start
Step2: Create text files [Link] and save with some contents & [Link] with Empty contents
Step3: open [Link] in ‘r’ mode
Step2: read the contents of [Link].
Step3: open [Link] in ‘a’ mode and will append the content of [Link] into [Link].
Step 6: open [Link]
Step 7: Stop

PROGRAM:
# Creating an output file in writing mode
output_file = open("myoutput [Link]", "w")
# Opening input file and scanning each line
# from input file and writing in output file
with open("myinput [Link]", "r") as scan:
output_file.write([Link]())
# Closing the output file
output_file.close()

OUTPUT:
[Link]:
Hi this is my first copy file python program

Myoutput [Link]:
Hi this is my first copy file python program

RESULT:
Thus the program to implement real-time/technical applications using File handling is written
and executed successfully.

17 ECS42002 – Python Programming Laboratory

[Link] CSE, AIML, DS


DATE:
[Link] : 9) Implementing real-time/technical applications using Exception handling: Divide by
zero error.

AIM : To write a program to implement real-time/technical applications using Exception


handling: Divide by zero error.

ALGORITHM :
Step 1: Get the input from the user and store the value in a & b
Step 2: Use try & catch with division statement and read the input values.
Step 3: Print the ZeroDivisionError

PROGRAM:
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
# Using exception object with the except statement
except Exception as e:
print("can't divide by zero")
print(e)

OUTPUT:
Enter a:10
Enter b:0
can't divide by zero
division by zero

RESULT:
Thus the program to implement real-time/technical applications using Exception handling is
written and executed successfully.

18 ECS42002 – Python Programming Laboratory

[Link] CSE, AIML, DS

You might also like