Lab Manual_Python Programming
Lab Manual_Python Programming
Lab Manual
Prepared by –Prof.P.T.Yewale
Lab Outcomes
LO. LO Cognitive
Number. level
1 Demonstrate the proficiency in basic python programming or Apply
Create and perform various operations on data structures like list,
tuple dictionaries and strings.
2 Apply Control Flow and Functions for efficient coding to solve Apply
problems.
3 Demonstrate proficiency in handling file operations, managing Apply
exceptions, and developing Python packages and executable files
for modular programming.
4 Illustrate the concept of Object-Oriented Programming used in Apply
python.
5 Design Graphical User Interface (GUI) applications, utilizing Create
appropriate Python libraries to create user-friendly interfaces.
6 Investigate and apply popular python libraries to conduct efficient Create
data handling tasks.
PO2.- Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
PO3.- Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
PO4.- Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
PO5.- Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex engineering
activities with an understanding of the limitations.
PO6.- The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
PO7.- Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.
PO9.- Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
PO11.- Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
PO12.- Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological change.
LO-PO Matrix-
LO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
1 3 3 2 1 3 1 3 2 1 1
2 3 3 2 1 3 1 3 2 1 1
3 3 3 2 1 3 1 3 2 1 1
4 3 3 2 1 3 1 3 2 1 1
5 3 3 2 1 3 1 3 2 1 1
6 3 3 2 1 3 1 3 2 1 1
LO-PSO Matrix-
LO PSO1 PSO2
1 - -
2 - -
3 - -
4 - -
5 - -
6 - -
12 Aim-Develop a Python program that reads a text file and prints words
of specified lengths (e.g., three, four, five, etc.) found within the file.
18 Aim- Write a Python script that prompts the user to enter their phone
number and email ID. It then employs Regular Expressions to verify
if these inputs adhere to standard phone number and email address
formats
23
Theory-
Name and greet" is a simple Python project that allows the user to input their name
and select a type of greeting. Based on their choice, the program outputs a
personalized greeting. This project is a great way to get started with Python
programming and practicing input/output functionality, if/else statements, and user
prompts.
The program can be customized and expanded by adding more greeting options or
by making the program more interactive, such as asking the user additional
questions or providing them with more choices. With a few modifications, this
project can be turned into a more complex chatbot or an interactive user interface
for greeting people.
Once the user enters their name, prompt them to select a type of greeting:
if choice == "1":
print(f"Hello {name}, wishing you a pleasant day from here")
else:
print("Invalid choice. Please enter 1, 2 or 3.")
That's it! This simple program prompts the user to enter their name and then allows
them to select a type of greeting. Based on their choice, a personalized greeting is
displayed.
Program Code-
# Python program that asks the user to enter their name, and then greet them.
Output of Program:-
Theory-
In this program we will calculate the area of different geometrical shapes based on
the user's choice and input. We will have five geometrical shapes: circle, rectangle,
triangle, square, and parallelogram. Users can choose the shape and provide the
required input fields to calculate its area.
We will use the following formulas to calculate the area of the circle, rectangle,
triangle, square, and parallelogram:
area = (float)3.14159*radius*radius;
area = (float)length*breadth;
s = (float)(a+b+c)/2;
area = (float)(sqrt(s*(s-a)*(s-b)*(s-c)));
area = (float)side*side;
area = (float)base*height;
We have used a switch case in all programs and calculated the area of a shape
depending on the input provided by users.
Program Code-
import math
choice = int(input(""))
# area of a circle
if choice==1:
area = math.pi*pow(radius,2)
#area of a rectangle
elif choice==2:
area = width*length
s= (a+b+c)/2
area = math.sqrt(s*(s-a)*(s-b)*(s-c))
#area of a Square
area = side*side
area = base*height
else:
print("Wrong Choice")
Output of Program:-
**********Choose an Option:*********
1: Area of the Circle
2: Area of the Rectangle
3: Area of the Triangle
4: Area of the Square
5: Area of the Parallelogram
1
Enter the radius of the Circle: 4
The area of the circle with radius 4.0 is : 50.27
Aim- Write a Python program to calculate the gross salary of an employee. The
program should prompt the user for the basic salary (BS) and then compute the
dearness allowance (DA) as 70% of BS, the travel allowance (TA) as 30% of BS,
and the house rent allowance (HRA) as 10% of BS. Finally, it should calculate the
gross salary as the sum of BS, DA, TA, and HRA and display the result.
Program Code-
return gross
# Driver code
if __name__ == '__main__':
# Function call
print(computeSalary(basic, grade));
Experiment no 4
Program Code-
Aim- Develop a Python program to manage a task list using lists and tuples,
including adding, removing, updating, and sorting tasks.
Program Code-
Accessing Tuples
print(x[0]) #welcom
print(x[1]) #to
print(x[2]) #wscube
print(x[3]) #tech
print(x[-1]) #tech
print(x[-2]) #wscube
print(x)
Concatenation of Tuples
x = (1, 2, 3, 4)
y = (5, 6, 7, 8)
z = x + y #tuple concatenation
print(z)
Slicing of Tuple
print(tu)
Deleting a Tuple
del tu[0]
print(tu)
Experiment no 6
Student Enrollment Manager *:
# as we do in mathematics
A = {0, 2, 4, 6, 8};
B = {1, 2, 3, 4, 5};
# union
print("Union :", A | B)
# intersection
# difference
print("Difference :", A - B)
# symmetric difference
class Student:
# Constructor
self.name = name
self.rollno = rollno
self.m1 = m1
self.m2 = m2
ls.append(ob)
print("\n")
# Search Function
for i in range(ls.__len__()):
if(ls[i].rollno == rn):
return i
# Delete Function
i = obj.search(rn)
del ls[i]
# Update Function
i = obj.search(rn)
roll = No
ls[i].rollno = roll
ls = []
obj = Student('', 0, 0, 0)
# ch = int(input("Enter choice:"))
# if(ch == 1):
# elif(ch == 2):
print("\n")
print("\nList of Students\n")
for i in range(ls.__len__()):
obj.display(ls[i])
# elif(ch == 3):
s = obj.search(2)
obj.display(ls[s])
# elif(ch == 4):
obj.delete(2)
print(ls.__len__())
for i in range(ls.__len__()):
obj.display(ls[i])
# elif(ch == 5):
obj.update(3, 2)
print(ls.__len__())
for i in range(ls.__len__()):
obj.display(ls[i])
# else:
Experiment no 8
if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))
Experiment no 9
num = 6
factorial = 1
factorial *= i
Experiment no 10
num = 11
if num > 1:
# Iterate from 2 to n // 2
if (num % i) == 0:
break
else:
else:
Experiment no 11
"1. Add\n" \
"2. Subtract\n" \
"3. Multiply\n" \
"4. Divide\n")
if select == 1:
add(number_1, number_2))
elif select == 2:
subtract(number_1, number_2))
elif select == 3:
multiply(number_1, number_2))
elif select == 4:
divide(number_1, number_2))
else:
print(word)
# Example of an exception
try:
print(result)
except ValueError as e:
except ZeroDivisionError as e:
print(e)
Using a Debugger*:
Aim-Demonstrate the use of a Python debugger (e.g., pdb or an IDE with debugging capabilities) on a
sample program with intentional errors. Guide students on setting breakpoints, stepping through code, and
examining variable values.
pdb supports:
Setting breakpoints
To start debugging within the program just insert import pdb, pdb.set_trace()
commands. Run your script normally, and execution will stop where we have
introduced a breakpoint. So basically we are hard coding a breakpoint on a line
below where we call set_trace(). With python 3.7 and later versions, there is a
built-in function called breakpoint() which works in the same manner. Refer
following example on how to insert set_trace() function.
Intentional error: As input() returns string, the program cannot use multiplication
on strings. Thus, it’ll raise ValueError.
import pdb
answer = a * b
return answer
pdb.set_trace()
sum = addition(x, y)
print(sum)
Output :
In the output on the first line after the angle bracket, we have the directory
path of our file, line number where our breakpoint is located,
and <module>. It’s basically saying that we have a breakpoint in exppdb.py
on line number 10 at the module level. If you introduce the breakpoint inside
the function, then its name will appear inside <>. The next line is showing
the code line where our execution is stopped. That line is not executed yet.
Then we have the pdb prompt. Now to navigate the code, we can use the
following commands :
where Display the stack trace and line number of the current line
Execute the current line and move to the next line ignoring function
next
calls
Now, to check the type of variable, just write whatis and variable name. In
the example given below, the output of type of x is returned as <class
string>. Thus typecasting string to int in our program will resolve the error.
b = 10
s=0
for i in range(a):
s += a / b
b -= 1
This statement loads your source code and stops execution on the first line of code.
We can navigate in pdb prompt using n (next), u (up), d (down). To debug and
navigate all throughout the Python code, we can navigate using the mentioned
commands.
a = 20
b = 10
s=0
for i in range(a):
s += a / b
b -= 1
Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 44
Output :
answer = a * b
return answer
result = multiply(x, y)
print(result)
Output :
Managing Breakpoints
After adding breakpoints with the help of numbers assigned to them, we can
manage the breakpoints using the enable and
disable and remove command. disable tells the debugger not to stop when
that breakpoint is reached, while enable turns on the disabled breakpoints.
Given below is the implementation to manage breakpoints using Example 4.
Experiment 16
Online Shopping System:
Aim-Develop classes for products, customers, and shopping carts. Include methods for adding items to
the cart, calculating total costs, processing orders, and managing inventory.
In this project, you will create a system to manage the products, orders, and customers in an
online store. You will define classes to represent the store, products, orders, and customers.
Here are the steps you can follow to implement this project:
1. Start by designing the layout of the store. Decide on the types of products that you want to
include, and the information that you want to store about each product (e.g. name, price,
Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 49
description, stock). You may also want to include categories or tags to help organize your
products.
class Product:
def __init__(self, name, price, description, stock):
self.name = name
self.price = price
self.description = description
self.stock = stock
def total_value(self):
return self.stock * self.price
def total_cost(self):
return self.quantity * self.product.price
def view_orders(self):
for order in self.orders:
print(order)
def sales_report(self):
total_sales = 0
for order in self.orders:
total_sales += order.total_cost()
return total_sales
def restock_report(self):
low_stock = []
for product in self.products:
if product.stock < 10:
low_stock.append(product)
return low_stock
customer1.place_order(product1, 1)
customer2.place_order(product2, 2)
customer1.view_orders()
Objective: To develop a
graphical user interface (GUI)
application for any use case.
Experiment 17
College Admission Registration Form:
Aim-The college admission registration form collects essential personal, educational, and contact
information from prospective students. Create a GUI as shown in Figure-1 that allows the user to input
his/her name, branch and favorite game. When the user clicks the Submit button, it should display the
output as illustrated.
Program Code-
#Now, we will use 'Label' method to add widget in the Registration Form and also use place()
method to set their positions.
lbl_0 = Label(base, text="Registration form", width=20,font=("bold",20))
#the place method in tkinter module helps user to set the geometry, that is, the dimensions of a
certain widget by placing them at a certain position
lbl_0.place(x=90,y=60)
#Using 'Label' widget to create Full name label and using place() method to set its position.
lbl_1 =Label(base, text= "FullName", width=20,font=("bold",10))
lbl_1.place(x=80,y=130)
#Using Enrty widget to make a text entry box for accepting the input string in text from user.
enter_1 = Entry(base)
#Using 'Label' widget to create Email label and using place() method to set its position.
lbl_3 = Label(base, text="Email", width=20,font=("bold",10))
lbl_3.place(x=68,y=180)
#Using Enrty widget to make a text entry box for accepting the input string in text from user.
enter_3 = Entry(base)
enter_3.place(x=240,y=180)
#Using 'Label' widget to create Gender label and using place() method to set its position.
lbl_4 = Label(base, text="Gender", width=20,font=("bold",10))
lbl_4.place(x=70,y=230)
#Using Radio button widget to create an option choosing button and using place() method to set
its position.
Radiobutton(base, text="Male", padx= 5, variable= vars, value=1).place(x=235, y=230)
Radiobutton(base, text="Female", padx= 20, variable= vars, value=2).place(x=290,y=230)
#Using 'Label' widget to create Countries label and using place() method, set its position.
lbl_5=Label(base, text ="Country", width=20,font=("bold",11))
lbl_5.place(x=70,y=280)
#the variable 'cv' is introduced to store the String Value, which by default is (empty) ""
cv = StringVar()
drplist = OptionMenu(base, cv, *list_of_cntry)
drplist.config(width=15)
cv.set('Select your Country')
drplist.place(x=240, y=280)
#Using 'Label' widget to create Language label and using place() method, set its position.
lbl_6=Label(base, text="Language", width=20,font=('bold',10))
lbl_6.place(x=75,y=330)
#the new variable 'vars1' is created to store Integer Value, which by default is 0.
vars1=IntVar()
#Using the Checkbutton widget to create a button and using place() method to set its position.
Checkbutton(base,text="English", variable = vars1).place(x=230,y=330)
#the new variable 'vars1' is created to store Integer Value, which by default is 0.
#Using the Button widget, we get to create a button for submitting all the data that has been
entered in the entry boxes of the form by the user.
Button(base, text='Submit' , width=20, bg="black",fg='white').place(x=180,y=380)
Output:
The output for the aforementioned Simple registration form's code, using Tkinter in Python
is attached below in the form of a screenshot.
Experiment 18
Program Code-
#validation of email id
import re
regex = re.compile(r'([A-Za-z0-9]+[.-_])*[A-Za-z0-9]+@[A-Za-z0-
9-]+(\.[A-Z|a-z]{2,})+')
def emailValid(email):
if re.fullmatch(regex, email):
print("The given mail is valid")
else:
print("The given mail is invalid")
emailValid("[email protected]")
emailValid("[email protected]")
emailValid("[email protected]")
import re
if match:
return True
return False
pattern = re.compile(r"(\+\d{1,3})?\s?\(?\d{1,4}\)?[\s.-]?\d{3}[\s.-]?\d{4}")
test_phone_numbers = [
"555-123-4567",
"02012345678",
Experiment 19
Extracting Data from Text *:
Aim- Create a program that reads a text file containing various data (e.g., names, emails, phone
numbers). Use regular expressions to extract specific types of data, such as email addresses,
phone numbers, dates (e.g., MM/DD/YYYY format).
Program Code-
import re
def find_emails(text):
patterns = [r"\S+@\S+"]
email_regex = re.compile(pattern)
emails = email_regex.findall(text)
print(email)
# Example usage
find_emails(text)
Output
Hr@[email protected]
[email protected]
import numpy as np
print(arr)
#Create a 2-D array containing two arrays with the values 1,2,3 and 4,5,6:
import numpy as np
print(arr)
import numpy as np
print(arr)
import numpy as np
newarr = arr.reshape(4, 3)
print(newarr)
#The outermost dimension will have 2 arrays that contains 3 arrays, each with 2
elements:
import numpy as np
newarr = arr.reshape(2, 3, 2)
print(newarr)
print(arr[1:5])
import numpy as np
print(arr[4:])
#Slice from the index 3 from the end to index 1 from the end:
import numpy as np
print(arr[-3:-1])
Array Indexing
#Get the first element from the following array:
import numpy as np
print(arr[0])
import numpy as np
print(arr[1])
#Get third and fourth elements from the following array and add them.
import numpy as np
print(arr[2] + arr[3])
import numpy as np
import numpy as np
#Access the third element of the second array of the first array:
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(arr[0, 1, 2])
import numpy as np
Experiment 21
Array Mathematics*:
Aim-Develop a Python script to create two arrays of the same shape and perform element-wise addition,
subtraction, multiplication, and division. Calculate the dot product and cross product of two vectors.
Python Code:
# Importing the NumPy library
import numpy as np
import numpy as np
a = 3 + 1j
b = 7 + 6j
print(np.dot(a, b))
Output:
(15+25j)
# Python Program illustrating
import numpy as np
Output:
[[5 4]
[9 6]]
import numpy as np
print(np.dot(b, a))
Output:
[[2 4]
[6 9]]
n=3
product = 0
return product
# Function to find
# Driver function
if __name__=='__main__':
vect_B = [2, 6, 5]
cross_P = []
print(dotProduct(vect_A, vect_B))
Output
Experiment 22
Statistical Operations*:
Aim-Write a Python program to calculate mean, median, standard deviation, variance, and correlation
coefficients of a given array.
import numpy as np
# Original array
array = np.arange(10)
print(array)
r1 = np.mean(array)
r2 = np.std(array)
import numpy as np
# Original array
array = np.arange(10)
print(array)
r1 = np.average(array)
r3 = np.mean((array - np.mean(array)) ** 2)
import numpy as np
# Original array
x = np.arange(5)
print(x)
r11 = np.mean(x)
r12 = np.average(x)
r21 = np.std(x)
r31 = np.var(x)
Experiment 23
Following task should be performing on a real-world dataset:
Task1- Loading and Inspecting Data: Load a CSV file containing information on global COVID-19
cases into a DataFrame. Display the first few rows, check the data types, and summarize basic statistics.
Task 2- Data Cleaning: Identify and handle missing values in the dataset. Remove any duplicate rows
and ensure data consistency.
Task 3-Data Aggregation: Perform aggregation operations to summarize data.
Task 4- Plotting graphs: Generate a line plot showing the trend / bar plot to compare data/ histogram to
show distribution/ scatter plot to examine relationships between variables.