Jawahar Education Society’s
A.C.Patil College of Engineering,Kharghar,Navi Mumbai.
Department of Humanity and Science
Sem-II Even SemYear 2024-25
Lab Manual
Course Name-Python Programming
Course Code-VSEC202
Prepared by –Prof.P.T.Yewale
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 1
Jawahar Education Society’s
A.C.Patil College of Engineering,Kharghar,Navi Mumbai.
Department of humanity and science
Sem-II Even Sem Year 2024-25
Course Name-Python Programming
Course Code-VSEC202
Lab Outcomes
Lab Outcomes: Learner will be able to
LO.Number LO Cognitive
. 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 Create
efficient data handling tasks.
Prof.PanditT.Yewale Dr.M.S.Selokar
Subject teacher Head of Department
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 2
Jawahar Education Society’s
A.C.Patil College of Engineering,Kharghar,Navi Mumbai.
Department of humanity and science
Program outcomes (POs)- Engineering & Technology
Engineering Graduates will be able to:
PO1.- Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and anengineering specialization to the solution of complex engineering problems.
PO2.- Problem analysis: Identify, formulate, review research literature, and analyze complex
engineeringproblems reaching substantiated conclusions using first principles of mathematics,
natural sciences, andengineering sciences.
PO3.- Design/development of solutions: Design solutions for complex engineering problems and
design systemcomponents or processes that meet the specified needs with appropriate
consideration for the public health andsafety, and the cultural, societal, and environmental
considerations.
PO4.- Conduct investigations of complex problems: Use research-based knowledge and research
methodsincluding design of experiments, analysis and interpretation of data, and synthesis of the
information to providevalid conclusions.
PO5.- Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineeringand IT tools including prediction and modeling to complex engineering
activities with an understanding of thelimitations.
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 professionalengineering practice.
PO7.- Environment and sustainability: Understand the impact of the professional engineering
solutions insocietal and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development.
PO8.- Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of theengineering practice.
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 3
PO9.- Individual and team work: Function effectively as an individual, and as a member or
leader in diverseteams, and in multidisciplinary settings.
PO10.- Communication: Communicate effectively on complex engineering activities with the
engineeringcommunity and with society at large, such as, being able to comprehend and write
effective reports and designdocumentation, make effective presentations, and give and receive
clear instructions.
PO11.- Project management and finance: Demonstrate knowledge and understanding of the
engineering andmanagement principles and apply these to one’s own work, as a member and
leader in a team, to manage projectsand in multidisciplinary environments.
PO12.- Life-long learning: Recognize the need for, and have the preparation and ability to
engage inindependent and life-long learning in the broadest context of technological change.
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 4
Jawahar Education Society’s
A.C.Patil College of Engineering,Kharghar,Navi Mumbai.
Department of humanity and science
Sem-II Even Sem Year 2024-25
Course Name-Python Programming
Course Code-VSEC202
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 - -
Prof.PanditT.YewaleDr.M.S.Selokar
Subject teacher Head of Department
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 5
Jawahar Education Society’s
A.C.Patil College of Engineering,Kharghar,Navi Mumbai.
Department of humanity and science
Sem-II Even Sem Year 2024-25
Course Name-Python Programming
Course Code-VSEC202
List of Experiments.
Exp Experiment name L PO
t no O
1 Aim-Write a python code to generate Personalized L1 1,2,3,4,5,7,9,10,11,1
Greeting. 2
2 Aim-Write a python program to calculate areas of any L1 1,2,3,4,5,7,9,10,11,1
geometric figures like circle, rectangle and triangle. 2
3 Aim- Write a Python program to calculate the gross salary L1 1,2,3,4,5,7,9,10,11,1
of an employee. The program should prompt the user for 2
the basic salary (BS) and then compute the dearness
allowance (DA) as 70% of BS, the travel allowance (TA)
as 30% of BS, the house rent allowance (HRA) as 10% of
BS and provident fund as 10% of BS. Finally, it should
calculate the gross salary as the algebraic sum of BS, DA,
TA, HRA and PF and display the result.
4 Aim-Write a Python program to explore basic arithmetic L1 1,2,3,4,5,7,9,10,11,1
operations. The program should prompt the user to enter 2
two numbers and then perform addition, subtraction,
multiplication, division, and modulus operations on those
numbers. The results of each operation should be
displayed to the user.
5 Aim- Develop a Python program to manage a task list L1 1,2,3,4,5,7,9,10,11,1
using lists and tuples, including adding, removing, 2
updating, and sorting tasks.
6 Aim-Create a Python code to demonstrate the use of sets L1 1,2,3,4,5,7,9,10,11,1
and perform set operations (union, intersection, 2
difference) to manage student enrollments in multiple
courses / appearing for multiple entrance exams like CET,
JEE, NEET etc.
7 Aim-Write a Python program to create, update, and L1 1,2,3,4,5,7,9,10,11,1
manipulate a dictionary of student records, including their 2
grades and attendance
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 6
8 Aim-Develop a Python program that takes a numerical L2 1,2,3,4,5,7,9,10,11,1
input and identifies whether it is even or odd, utilizing 2
conditional statements and loops.
9 Aim-Design a Python program to compute the factorial of L2 1,2,3,4,5,7,9,10,11,1
a given integer N. 2
10 Aim-Using function, write a Python program to analyze L2 1,2,3,4,5,7,9,10,11,1
the input number is prime or not. 2
11 Aim-Implement a simple Python calculator that takes user L2 1,2,3,4,5,7,9,10,11,1
input and performs basic arithmetic operations (addition, 2
subtraction, multiplication, division) using functions.
12 Aim-Develop a Python program that reads a text file and L3 1,2,3,4,5,7,9,10,11,1
prints words of specified lengths (e.g., three, four, five, 2
etc.) found within the file.
13 Aim-Create a executable file for any program developed L3 1,2,3,4,5,7,9,10,11,1
in earlier practical. 2
14 Aim-Write a Python program that takes two numbers as L3 1,2,3,4,5,7,9,10,11,1
input and performs division. Implement exception 2
handling to manage division by zero and invalid input
errors gracefully.
15 Aim-Demonstrate the use of a Python debugger (e.g., pdb L3 1,2,3,4,5,7,9,10,11,1
or an IDE with debugging capabilities) on a sample 2
program with intentional errors. Guide students on setting
breakpoints, stepping through code, and examining
variable values.
16 Aim-Develop classes for products, customers, and L4 1,2,3,4,5,7,9,10,11,1
shopping carts. Include methods for adding items to the 2
cart, calculating total costs, processing orders, and
managing inventory.
17 Aim-The college admission registration form collects L5 1,2,3,4,5,7,9,10,11,1
essential personal, educational, and contact information 2
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.
18 Aim- Write a Python script that prompts the user to enter L5 1,2,3,4,5,7,9,10,11,1
their phone number and email ID. It then employs Regular 2
Expressions to verify if these inputs adhere to standard
phone number and email address formats
19 Aim- Create a program that reads a text file containing L5 1,2,3,4,5,7,9,10,11,1
various data (e.g., names, emails, phone numbers). Use 2
regular expressions to extract specific types of data, such
as email addresses, phone numbers, dates (e.g.,
MM/DD/YYYY format).
20 Aim-Write a Python program to create a 1D, 2D, and 3D L6 1,2,3,4,5,7,9,10,11,1
NumPy array. Perform basic operations like reshaping, 2
slicing, and indexing.
21 Aim-Develop a Python script to create two arrays of the L6 1,2,3,4,5,7,9,10,11,1
same shape and perform element-wise addition, 2
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 7
subtraction, multiplication, and division. Calculate the dot
product and cross product of two vectors.
22 Aim-Write a Python program to calculate mean, median, L6 1,2,3,4,5,7,9,10,11,1
standard deviation, variance, and correlation coefficients 2
of a given array.
Prof.PanditT.Yewale Dr.M.S.Selokar
Subject teacher Head of Department
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 8
Objective:
To enable learners to transition their
understanding of basic programming
constructs from C to Python by focusing on
Python's syntax, variables, data types,
operators, and input/output functions, and
comparing these elements with their
equivalents in C
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 9
Jawahar Education Society’s
A.C.Patil college of Engineering,Kharghar,Navi Mumbai
Humanity and Science Department
First Year Engineering. Academic Year 2024-25 EvenSem
Subject-Python Programming9(Course code-VSEC202)
PRN No.: ROLL No.:
Name of the Student:
Branch:
Practical Batch:
Practical No.:
Aim:
Date of Performance: -
Evaluation Criteria Marks Signature of Instructor with Date
Lab Performance (3)
Journal Performance (3)
Punctuality (3)
Attainment Level (Out of 9)
Experiment no 1
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 10
Personalized Greeting Generator* -
Aim-Write a python code to generate Personalized Greeting.
Requirement:Python 3.13.0
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 input, the program outputs a personalized greeting. This project
is a great way to get started with Python programming and practicing input/output functionality
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.
Open your Python development environment (such as IDLE or PyCharm).
Create a new Python file and name it as greeting.py
Start by printing a welcome message to the user:
print("Welcome to the name and greet program!")
Next, prompt the user to enter their name:
name = input("Please enter your name: ")
Once the user enters their name, prompt them to enter greeting message:
message=input("Please enter greeting message")
Once the user enters their name and greeting message print greeting message.
print(f"{message}",name)
Finally, print a thank you message to the user:
print("Thanks for using the name and greet program!")
Save the file and run the program to test it out.
That's it! This simple program prompts the user to enter their name and greeting message and
then personalized greeting message is displayed.
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 11
Algorithm
1. Start
2. Prompt the user to enter their name
3. Read the input and store it in a variable (name)
4. Display a greeting message with the user's name
5. End
Flow Chart:
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 12
Flowchart Steps for Name and Greet Program
1. Start (Oval shape)
2. Display Welcome Message (Parallelogram for output)
o Print: "Welcome to the name and greet program!"
3. Ask User for Name (Parallelogram for input)
o name = input("Please enter your name: ")
4. Ask User for Greeting Message (Parallelogram for input)
o message = input("Please enter greeting message: ")
5. Display Greeting Message (Parallelogram for output)
o Print: "{message} {name}"
6. End (Oval shape)
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 13
Experiment no. 1
Aim: Write a python code to generate Personalized Greeting.
Requirement: Python 3.13.0
Program Code:
# Getting current date and time using now().
# importing datetime module for now()
import datetime
# using now() to get current time
current_time = datetime.datetime.now()
# Printing value of now.
print("Name of student:Pandit Yewale")
print("Roll no:1111 Batch: D1 Branch:AI&DS")
print("Current date and time is:", current_time)
cstr='*'
print(cstr.ljust(70,'*'))
#(Above program code should be included in each program at the start of program code)
# Python program that asks the user to enter their name, and then greet them.
print("Welcome to the name and greet program!")
name = input("Please enter your name: ")
message=input("Please enter greeting message: ")
print(f"{message}",name)
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 14
Output:
Conclusion:
Thus we understood how to write a python code to generate Personalized Greeting.
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 15
Experiment no 2
Calculating Areas of Geometric Figures* -
Aim-Write a python program to calculate areas of any geometric figures like circle, rectangle ,
triangle, square and Parallelogram
Requirement: Python 3.13.0
Theory-
In this program we will calculate the area of different geometrical shapes based on the input. We
will have five geometrical shapes: circle, rectangle, triangle, square, and parallelogram. Users
can see the shapename 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 of circle = 3.1459* radius*radius
The logic to calculate the area of the circle will be
area = (float)3.14159*radius*radius;
Area of the rectangle = length* breadth
The logic to calculate the area of the circle will be
area = (float)length*breadth;
Area of a triangle (with three sides given a, b, and c) = Square root of [s(s-a)(s-b)(s-
c)] , where s = (a+b+c)/2
The logic to calculate the area of the circle will be
s = (float)(a+b+c)/2;
area = (float)(sqrt(s*(s-a)*(s-b)*(s-c)));
Area of a square = side*side
The logic to calculate the area of the circle will be
area = (float)side*side;
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 16
Area of Parallelogram = base*height
The logic to calculate the area of the circle will be:
area = (float)base*height;
We have calculated the area of a shape depending on the input provided by users.
Algorithm:
1. Start
2. Calculate the area of a Circle
o Ask for the radius
o Compute π × r²
o Display the result
3. Calculate the area of a Rectangle
o Ask for length and width
o Compute length × width
o Display the result
4. Calculate the area of a Triangle
o Ask for base and height
o Compute 0.5 × base × height
o Display the result
5. Calculate the area of a Square
o Ask for side length
o Compute side²
o Display the result
6. Calculate the area of a Parallelogram
o Ask for base and height
o Compute base × height
o Display the result
7. End
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 17
Flow Chart:
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 18
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 19
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 20
Experiment no 2
Aim: Write a python program to calculate areas of any geometric figures like circle, rectangle
and triangle.
Requirement: Python 3.13.0
Program Code:
# Getting current date and time using now().
# importing datetime module for now()
import datetime
# using now() to get current time
current_time = datetime.datetime.now()
# Printing value of now.
print("Name of student:Pandit Yewale")
print("Roll no:1111 Batch: D1 Branch:AI&DS")
print("Current date and time is:", current_time)
cstr='*'
print(cstr.ljust(70,'*'))
#(Above program code should be included in each program at the start of program code)
# Area Calculator in Python
import math
print("**********Program to calculate area of geometric figures********* ");
# area of a circle
print("\n1: Area of the Circle");
# input circle radius
radius = float(input(" Enter the radius of the Circle: "))
area = math.pi*radius*radius
print(f"The area of the circle with radius {radius} is :",area)
print("\n2: Area of the Rectangle ");
#area of a rectangle
width =float(input("Enter the width of the rectangle: "))
length = float(input("Enter the length of the rectangle: "))
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 21
area = width*length
print(f"The area of the rectangle with {width} and {length} is",area)
print("\n3: Area of the Triangle ");
# area of a triangle using Heron's formula
a=float(input("Enter the first side of the triangle: "))
b=float(input("Enter the second side of the triangle: "))
c=float(input("Enter the third side of the triangle: "))
s= (a+b+c)/2
area = math.sqrt(s*(s-a)*(s-b)*(s-c))
print(f"The area of the triangle with sides {a},{b}, {c} is ",area)
print("\n4: Area of the Square ");
#area of a Square
side =float(input("Enter the side of the square: "))
area = side*side
print(f"The area of the square with side{side} is",area)
print("\n5: Area of the Parallelogram ");
#area of a Parallelogram
base =float(input("Enter the base of the parallelogram: "))
height = float(input("Enter the height of the parallelogram: "))
area = base*height
print(f"The area of the parallelogram with {base} and {height} is",area)
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 22
Output of Program:-
Conclusion:
Thus we understood how to write a python program to calculate areas of any geometric figures
like circle, rectangle and triangle.
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 23
Experiment no 3
Calculating Gross Salary of an Employee*:
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 also provident fund (PF) as 10% of BS. Finally, it should calculate the gross salary as the
algebraic sum of BS, DA, TA,HRA and PF and display the result.
Requirement: Python 3.13.0
Theory-
In this program we will calculate the gross salary of an employee based on the input given from
keyboard. We have to 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 also provident fund (PF)
as 10% of BS. Gross salary of employee can be calculated with the algebraic sum of BS, DA,
TA, ,HRA and PF and can be display as result.
We will use the following formulas to calculate the dearness allowance (DA) as 70% of BS
Dearness allowance (DA) = 70% X basic salary (BS)
The logic to calculate the Dearness allowance (DA)will be
DA = 0.7*float(BS)
We will use the following formulas to calculate house rent allowance (HRA) as 10% of BS
House rent allowance (HRA) = 10% X basic salary (BS)
The logic to calculate the house rent allowance (HRA) will be
HRA = 0.1*float(BS)
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 24
We will use the following formulas to calculate the travel allowance (TA) as 30% of BS
Travel allowance (TA) = 30% X basic salary (BS)
The logic to calculate the travel allowance (TA) will be
TA = 0.3*float(BS)
We will use the following formulas to calculate provident fund (PF) as 10% of BS
Provident fund (PF) = 10% X basic salary (BS)
The logic to calculate the provident fund (PF) will be
PF = 0.1*float(BS)
Gross salary of employee can be calculated with the algebraic sum of BS, DA, TA, HRA and PF
as
Gross salary(GS) = BS+DA+TA-PF
The logic to calculate the Gross salary (GS) will be
Gross salary(GS) = BS+DA+TA-PF
Finally print gross salary of employee with name of Employee
print(f"salary of employee {name}",gross)
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 25
Algorithm:-
Step 1:
Inputs:
The program asks for the employee's name.
It asks for the basic salary of the employee.
Step 2:
Allowance and Deduction Calculations:
HRA (House Rent Allowance): 10% of the basic salary.
DA (Dearness Allowance): 70% of the basic salary.
TA (Travel Allowance): 30% of the basic salary.
PF (Provident Fund): 10% of the basic salary.
Step 3:
Gross Salary Calculation:
The gross salary is calculated by adding the basic salary, HRA, DA, and TA, and then
subtracting the PF deduction.
Step 4:
Output:
The program displays the salary details including basic salary, HRA, DA, TA, PF
deduction, and the final gross salary.
Flow Chart:
Flowchart Steps for Salary Calculation Program
1. Start (Oval shape)
2. Input Employee Name (Parallelogram for input)
3. Input Basic Salary (Parallelogram for input)
4. Check if Salary is Valid (Decision Diamond)
o If salary is negative, display an error message and end.
o If salary is valid, proceed to the next step.
5. Calculate Allowances and Deductions (Rectangle for process)
o Compute House Rent Allowance (HRA) → hra = 0.10 * basic
o Compute Dearness Allowance (DA) → da = 0.70 * basic
o Compute Travel Allowance (TA) → ta = 0.30 * basic
o Compute Provident Fund (PF) → pf = 0.10 * basic
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 26
6. Compute Gross Salary (Rectangle for process)
o Gross Salary = basic + hra + da + ta - pf
7. Display Salary Details (Parallelogram for output)
o Show all calculated values (Basic, HRA, DA, TA, PF, Gross Salary)
8. End (Oval shape)
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 27
Experiment no 3
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 also provident fund (PF) as 10% of BS. Finally, it should calculate the gross salary as the
algebraic sum of BS, DA, TA,HRA and PF and display the result.
Requirements: Python 3.13.0
Program Code:
# Getting current date and time using now().
# importing datetime module for now()
import datetime
# using now() to get current time
current_time = datetime.datetime.now()
# Printing value of now.
print("Name of student:Pandit Yewale")
print("Roll no:1111 Batch: D1 Branch:AI&DS")
print("Current date and time is:", current_time)
cstr='*'
print(cstr.ljust(70,'*'))
#(Above program code should be included in each program at the start of program code)
# Python3 program to calculate the salary
import math
# Input the employee name and basic salary
name = input("Enter the name of Employee Mr/Mrs: ")
basic = float(input("Enter basic Salary in Rs.: "))
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 28
# Calculate allowances and deductions
hra = 0.10 * basic # House Rent Allowance (HRA)
da = 0.70 * basic # Dearness Allowance (DA)
ta = 0.30 * basic # Travel Allowance (TA)
pf = 0.10 * basic # Provident Fund (PF)
# Calculate gross salary
gross = round(basic + hra + da + ta - pf, 2)
# Output the salary details
print(f"\nSalary details of Employee {name}:")
print(f"Basic Salary: Rs. {basic}")
print(f"HRA: Rs. {hra}")
print(f"DA: Rs. {da}")
print(f"TA: Rs. {ta}")
print(f"PF Deduction: Rs. {pf}")
print(f"Gross Salary: Rs. {gross}")
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 29
Output:
Conclusion:
Thus we understood how to write a Python program to calculate the gross salary of an employee.
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 30
Experiment no 4
Exploring Basic Arithmetic Operations in Python*:
Aim-Write a Python program to explore basic arithmetic operations. The program should prompt
the user to enter two numbers and then perform addition, subtraction, multiplication, division,
and modulus operations on those numbers. The results of each operation should be displayed to
the user.
Requirement: Python 3.13.0
Theory:
This is basic python program for all beginners in python programming language. It simply takes
two integer numbers and performs arithmetic operations like addition, subtraction, multiplication,
division, floor division, modulus and exponential(power) on them.
We will use the following formulas to calculate
Addition of two numbers which are stored in variables num1 and num2 and result is stored in
add variable
The logic to calculate the addition is
Add=num1+num2
Subtraction of two numbers which are stored in variables num1 and num2 and result is stored in
dif variable
The logic to calculate the addition is
dif =num1-num2
Multiplication of two numbers which are stored in variables num1 and num2 and result is stored
in mul variable
The logic to calculate the addition is
mul=num1*num2
Division of two numbers which are stored in variables num1 and num2 and result is stored in div
variable
The logic to calculate the addition is
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 31
div=num1/num2
Floor division of two numbers which are stored in variables num1 and num2 and result is stored
in floor_div variable
The logic to calculate the addition is
floor_div =num1//num2
Power of two numbers which are stored in variables num1 and num2 and result is stored in
power variable
The logic to calculate the addition is
power=num1**num2
Modulus of two numbers which are stored in variables num1 and num2 and result is stored in
modulus variable
The logic to calculate the addition is
modulus=num1%num2
Finally print each operation
print('Sum of ', num1, 'and', num2, 'is :', add)
print('Difference of ', num1, 'and', num2, 'is :', dif)
print('Product of ', num1, 'and', num2, 'is :', mul)
print('Division of ', num1, 'and', num2, 'is :', div)
print('Floor Division of ', num1, 'and', num2, 'is :', floor_div)
print('Exponent of ', num1, 'and', num2, 'is :', power)
print('Modulus of ', num1, 'and', num2, 'is :', modulus)
Algorithm:
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 32
Step 1: Read two input integers using input() or raw_input().
Step 2: Addition operation using + operator, num1 + num2 adds 2 numbers.
Step 3:Subtraction operation using - operator, num1 - num2 right hand operand from left
hand operand.
Step 4:Multiplication operation using * operator, num1 * num2 multiplies 2 numbers.
Step 5:Division operation using / operator, num1 / num2 divides left hand operand by right
hand operand.
Step 6:Floor Division operation using // operator, num1 // num2 divides left hand operand by
right hand operand, here it removes the values after decimal point.
Step 7:Exponential operation using ** operator, num1 ** num2 returns value of num1 num2
Step 8: Modulus % operator when applied returns the remainder when left hand operand is
divided by right hand operand num1 % num2.
Step 9: Print the result of each operation.
Algorithm:-
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 33
Flow Chart:
Flowchart Steps:
1. Start (Oval shape)
2. Input First Number (num1) (Parallelogram for input)
3. Input Second Number (num2) (Parallelogram for input)
4. Perform Arithmetic Operations (Rectangle for process):
o Addition: add = num1 + num2
o Subtraction: dif = num1 - num2
o Multiplication: mul = num1 * num2
o Division: div = num1 / num2
o Floor Division: floor_div = num1 // num2
o Exponentiation: power = num1 ** num2
o Modulus: modulus = num1 % num2
5. Display Results (Parallelogram for output):
o Print all the calculated results.
6. End (Oval shape)
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 34
Experiment no 4
Aim-Write a Python program to explore basic arithmetic operations. The program should prompt
the user to enter two numbers and then perform addition, subtraction, multiplication, division,
and modulus operations on those numbers. The results of each operation should be displayed to
the user.
Requirement: Python 3.13.0
Program Code-
# Getting current date and time using now().
# importing datetime module for now()
import datetime
# using now() to get current time
current_time = datetime.datetime.now()
# Printing value of now.
print("Name of student:Pandit Yewale")
print("Roll no:1111 Batch: D1 Branch:AI&DS")
print("Current date and time is:", current_time)
#(Above program code should be included in each program at the start of program code)
cstr='*'
print(cstr.ljust(70,'*'))
#Python program to explore basic arithmetic operations.
num1 = int(input(“Enter First number: “))
num2 = int(input(“Enter Second number “))
#basic arithmetic operations
add = num1 + num2
dif = num1 - num2
mul = num1 * num2
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 35
div = num1 / num2
floor_div = num1 // num2
power = num1 ** num2
modulus = num1 % num2
print("1.Addition: ")
print('Sum of ', num1, 'and', num2, 'is :', add)
print("2.Substration: ")
print('Difference of ', num1, 'and', num2, 'is :', dif)
print("3.Multiplaction: ")
print('Product of ', num1, 'and', num2, 'is :', mul)
print("4.Division: ")
print('Division of ', num1, 'and', num2, 'is :', div)
print("5.Floor Division: ")
print('Floor Division of ', num1, 'and', num2, 'is :', floor_div)
print("6.Exponent: ")
print('Exponent of ', num1, 'and', num2, 'is :', power)
print("7.Modulus: ")
print('Modulus of ', num1, 'and', num2, 'is :', modulus)
Output:
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 36
Conclusion:
Thus we understood how to write a Python program to explore basic arithmetic operations.
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 37
Objective:
Mastering Python New Data
Structures for Practical
Applications
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 38
Experiment no 5
Task List Manager*:
Aim- Develop a Python program to manage a task list using lists and tuples, including adding,
removing, updating, and sorting tasks.
Requirement: Python 3.13.0
Theory:
Python List:
In Python, lists allow us to store multiple items in a single variable. For example, if you need to
store the ages of all the students in a class, you can do this task using a list.Lists are similar to
arrays (dynamic arrays that allow us to store items of different data types) in other programming
languages.
List Characteristics
In Python, lists are:
Ordered - They maintain the order of elements.
Mutable - Items can be changed after creation.
Allow duplicates - They can contain duplicate values.
Lists are Ordered, mutable collections that can contain items of different types.
Example:
numbers = [1, 2, 3, 4, 5]
mixed = [1, "two", 3.0, [4, 5]]
Create a Python List
We create a list by placing elements inside square brackets [], separated by commas.
For example,
# a list of three elements
ages = [19, 26, 29]
print(ages)
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 39
Output:
[19, 26, 29]
Here, the ages List has three items.
List Items of Different Types
Python lists are very flexible. We can also store data of different data types in a list.
For example,
# a list containing strings, numbers and another list
student = ['Jack', 32, 'Computer Science', [2, 4]]
print(student)
# an empty list
empty_list = []
print(empty_list)
Output:
['Jack', 32, 'Computer Science', [2, 4]]
[]
Access List Elements
Each element in a list is associated with a number, known as an index. The index of first item
is 0, the index of second item is 1, and so on.
Index of List Elements
We use these indices to access items of a list.
For example,
languages = ['Python', 'Swift', 'C++']
# access the first element
print('languages[0] =', languages[0])
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 40
# access the third element
print('languages[2] =', languages[2])
Output:
languages[0] = Python
languages[2] = C++
Access List Elements
Negative Indexing
In Python, a list can also have negative indices. The index of the last element is -1, the second
last element is -2 and so on.
Python Negative Indexing
For example.
languages = ['Python', 'Swift', 'C++']
# access the last item
print('languages[-1] =', languages[-1])
# access the third last item
print('languages[-3] =', languages[-3])
Output:
languages[-1] = C++
languages[-3] = Python
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 41
Slicing of a List in Python
If we need to access a portion of a list, we can use the slicing operator, :.
For example,
my_list = ['p', 'r', 'o', 'g', 'r', 'a', 'm']
print("my_list =", my_list)
# get a list with items from index 2 to index 4 (index 5 is not included)
print("my_list[2: 5] =", my_list[2: 5])
# get a list with items from index 2 to index -3 (index -2 is not included)
print("my_list[2: -2] =", my_list[2: -2])
# get a list with items from index 0 to index 2 (index 3 is not included)
print("my_list[0: 3] =", my_list[0: 3])
Output:
my_list = ['p', 'r', 'o', 'g', 'r', 'a', 'm']
my_list[2: 5] = ['o', 'g', 'r']
my_list[2: -2] = ['o', 'g', 'r']
my_list[0: 3] = ['p', 'r', 'o']
Omitting Start and End Indices in Slicing
If you omit the start index, the slicing starts from the first element. Similarly, if you omit the last
index, the slicing ends at the last element.
For example,
my_list = ['p', 'r', 'o', 'g', 'r', 'a', 'm']
print("my_list =", my_list)
# get a list with items from index 5 to last
print("my_list[5: ] =", my_list[5: ])
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 42
# get a list from the first item to index -5
print("my_list[: -4] =", my_list[: -4])
# omitting both start and end index
# get a list from start to end items
print("my_list[:] =", my_list[:])
Output:
my_list = ['p', 'r', 'o', 'g', 'r', 'a', 'm']
my_list[5: ] = ['a', 'm']
my_list[: -4] = ['p', 'r', 'o']
my_list[:] = ['p', 'r', 'o', 'g', 'r', 'a', 'm']
Add Elements to a Python List
As mentioned earlier, lists are mutable and we can change items of a list. To add an item to the
end of a list, we can use the list append() method.
For example,
fruits = ['apple', 'banana', 'orange']
print('Original List:', fruits)
fruits.append('cherry')
print('Updated List:', fruits)
Output:
Original List: ['apple', 'banana', 'orange']
Updated List: ['apple', 'banana', 'orange', 'cherry']
Add Elements at the Specified Index
We can insert an element at the specified index to a list using the insert() method. For example,
fruits = ['apple', 'banana', 'orange']
print("Original List:", fruits)
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 43
fruits.insert(2, 'cherry')
print("Updated List:", fruits)
Output:
Original List: ['apple', 'banana', 'orange']
Updated List: ['apple', 'banana', 'cherry', 'orange']
Add Elements to a List From Other Iterables
The list extend() method method all the items of the specified iterable, such as list, tuple,
dictionary or string , to the end of a list.
For example,
numbers = [1, 3, 5]
print('Numbers:', numbers)
even_numbers = [2, 4, 6]
print('Even numbers:', numbers)
# adding elements of one list to another
numbers.extend(even_numbers)
print('Updated Numbers:', numbers)
Output:
Numbers: [1, 3, 5]
Even numbers: [2, 4, 6]
Updated Numbers: [1, 3, 5, 2, 4, 6]
Change List Items(Update List)
We can change the items of a list by assigning new values using the = operator. For example,
colors = ['Red', 'Black', 'Green']
print('Original List:', colors)
# change the first item to 'Purple'
colors[2] = 'Purple'
# change the third item to 'Blue'
colors[2] = 'Blue'
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 44
print('Updated List:', colors)
Output:
Original List: ['Red', 'Black', 'Green']
Updated List: ['Purple', 'Black', 'Blue']
Here, we have replaced
the element at index 0 to ‘Purple’
the element at index 2 to ‘Blue’
Remove an Item From a List
We can remove the specified item from a list using the remove() method.
For example,
numbers = [2,4,7,9]
# remove 4 from the list
numbers.remove(4)
print(numbers)
Output:
[2, 7, 9]
Remove One or More Elements of a List
Instead of using the remove() method, we can delete an item from a list using the del statement.
The del statement can also be used to delete multiple elements or even the entire list.
names = ['John', 'Eva', 'Laura', 'Nick', 'Jack']
# delete the item at index 1
del names[1]
print(names)
# delete items from index 1 to index 2
del names[1: 3]
print(names)
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 45
# delete the entire list
del names
# Error! List doesn't exist.
print(names)
Output:
['John', 'Laura', 'Nick', 'Jack']
['John', 'Jack']
Traceback (most recent call last):
File "", line 15, in
NameError: name 'names' is not defined
Python List Length
To find the number of elements (length) of a list, we can use the built-in len() function.
For example,
cars = ['BMW', 'Mercedes', 'Tesla']
print('Total Elements:', len(cars))
Output:
Total Elements: 3
Iterating Through a List
We can use a for loop to iterate over the elements of a list.
For example,
fruits = ['apple', 'banana', 'orange']
# iterate through the list
for fruit in fruits:
print(fruit)
Output:
apple
banana
orange
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 46
Python List Methods
Python has many useful list methods that make it really easy to work with lists.
Method Description
append() Adds an item to the end of the list
extend() Adds items of lists and other iterables to the end of the list
insert() Inserts an item at the specified index
remove() Removes the specified value from the list
pop() Returns and removes item present at the given index
clear() Removes all items from the list
index() Returns the index of the first matched item
count() Returns the count of the specified item in the list
sort() Sorts the list in ascending/descending order
reverse() Reverses the item of the list
copy() Returns the shallow copy of the list
Experiment no 5
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 47
Aim- Develop a Python program to manage a task list using lists and tuples, including adding,
removing, updating, and sorting tasks.
Requirement: Python 3.13.0
Program Code:
#List Manager
# Getting current date and time using now().
# importing datetime module for now()
import datetime
# using now() to get current time
current_time = datetime.datetime.now()
# Printing value of now.
print("Name of student:Pandit Yewale")
print("Roll no:1111 Batch: D1 Branch:AI&DS")
print("Current date and time is:", current_time)
#(Above program code should be included in each program at the start of program code)
cstr='*'
print(cstr.ljust(70,'*'))
class ListManager:
def __init__(self):
self.items = []
defadd_item(self, item):
"""Add an item to the list"""
self.items.append(item)
print(f"Item '{item}' added to the list.")
defremove_item(self, item):
"""Remove an item from the list"""
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 48
if item in self.items:
self.items.remove(item)
print(f"Item '{item}' removed from the list.")
else:
print(f"Item '{item}' not found in the list.")
defupdate_item(self, old_item, new_item):
"""Update an item in the list"""
if old_item in self.items:
index = self.items.index(old_item)
self.items[index] = new_item
print(f"Item '{old_item}' updated to '{new_item}'.")
else:
print(f"Item '{old_item}' not found in the list.")
defsort_list(self):
"""Sort the list"""
self.items.sort()
print("List sorted.")
defdisplay_list(self):
"""Display the current list"""
print("Current list:", self.items)
# Main program to interact with the ListManager class
def main():
manager = ListManager()
while True:
print("\nMenu:")
print("1. Add item")
print("2. Remove item")
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 49
print("3. Update item")
print("4. Sort list")
print("5. Display list")
print("6. Exit")
choice = input("Enter your choice (1-6): ")
if choice == '1':
item = input("Enter the item to add: ")
manager.add_item(item)
elif choice == '2':
item = input("Enter the item to remove: ")
manager.remove_item(item)
elif choice == '3':
old_item = input("Enter the item to update: ")
new_item = input("Enter the new item: ")
manager.update_item(old_item, new_item)
elif choice == '4':
manager.sort_list()
elif choice == '5':
manager.display_list()
elif choice == '6':
print("Exiting the program.")
break
else:
print("Invalid choice, please try again.")
if __name__ == "__main__":
main()
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 50
Output:
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 51
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 52
Python Tuple
A tuple is a collection similar to a Python list. The primary difference is that we cannot modify a
tuple once it is created.
Tuple Characteristics
Tuples are:
Ordered - They maintain the order of elements.
Immutable - They cannot be changed after creation.
Allow duplicates - They can contain duplicate values.
Create a Python Tuple
We create a tuple by placing items inside parentheses ().
For example,
numbers = (1, 2, -5)
print(numbers)
Output:
(1, 2, -5)
Create a Tuple Using tuple() Constructor
We can also create a tuple using a tuple() constructor.
For example,
tuple_constructor = tuple(('Jack', 'Maria', 'David'))
print(tuple_constructor)
Output:
('Jack', 'Maria', 'David')
Different Types of Python Tuples
Here are the different types of tuples we can create in Python.
Empty Tuple
# create an empty tuple
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 53
empty_tuple = ()
print(empty_tuple)
Output:
()
Tuple of different data types
# tuple of string types
names = ('James', 'Jack', 'Eva')
print (names)
# tuple of float types
float_values = (1.2, 3.4, 2.1)
print(float_values)
Output:
('James', 'Jack', 'Eva')
(1.2, 3.4, 2.1)
Tuple of mixed data types
# tuple including string and integer
mixed_tuple = (2, 'Hello', 'Python')
print(mixed_tuple)
Output:
(2, 'Hello', 'Python')
Access Tuple Items
Each item in a tuple is associated with a number, known as a index.
The index always starts from 0, meaning the first item of a tuple is at index 0, the second item is
at index 1, and so on.
Index of Tuple Item
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 54
Access Items Using Index
We use index numbers to access tuple items.
For example,
languages = ('Python', 'Swift', 'C++')
# access the first item
print(languages[0]) # Python
# access the third item
print(languages[2]) # C++
Output:
Python
C++
Access Tuple Items
Tuple Cannot be Modified
Python tuples are immutable (unchangeable). We cannot add, change, or delete items of a tuple.
If we try to modify a tuple, we will get an error.
For example,
cars = ('BMW', 'Tesla', 'Ford', 'Toyota')
# trying to modify a tuple
cars[0] = 'Nissan' # error
print(cars)
Output:
ERROR!
Traceback (most recent call last):
File "<main.py>", line 7
C++
^
SyntaxError: invalid syntax
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 55
Python Tuple Length
We use the len() function to find the number of items present in a tuple.
For example,
cars = ('BMW', 'Tesla', 'Ford', 'Toyota')
print('Total Items:', len(cars))
Output:
Total Items: 4
Iterate Through a Tuple
We use the for loop to iterate over the items of a tuple.
For example,
fruits = ('apple','banana','orange')
# iterate through the tuple
for fruit in fruits:
print(fruit)
Output:
apple
banana
orange
Check if an Item Exists in the Tuple
We use the in keyword to check if an item exists in the tuple.
For example,
colors = ('red', 'orange', 'blue')
print('yellow' in colors) # False
print('red' in colors) # True
Output:
False
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 56
True
Here,
yellow is not present in colors, so, ’yellow’ in colors evaluates to False
red is present in colors, so, ’red’ in colors evaluates to True
Change Tuple Items
Python Tuples are immutable - we cannot change the items of a tuple once created.
If we try to do so, we will get an error.
For example,
fruits = ('apple', 'cherry', 'orange')
# trying to change the second item to 'banana'
fruits[1] = 'banana'
print(fruits)
Output:
TypeError: 'tuple' object does not support item assignment
Delete Tuples
We cannot delete individual items of a tuple. However, we can delete the tuple itself
using the del statement.
For example,
animals = ('dog', 'cat', 'rat')
# deleting the tuple
del animals
Here, we have deleted the animals tuple.
Create a Python Tuple with One Item
When we want to create a tuple with a single item, we might do the following:
For example,
var = ('Hello')
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 57
print(var) # string
Output:
Hello
But this would not create a tuple; instead, it would be considered a string.
To solve this, we need to include a trailing comma after the item.
For example,
var = ('Hello',)
print(var) # tuple
Output:
('Hello',)
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 58
Program Code-
# Getting current date and time using now().
# importing datetime module for now()
import datetime
# using now() to get current time
current_time = datetime.datetime.now()
# Printing value of now.
print("Name of student:Pandit Yewale")
print("Roll no:1111 Batch: D1 Branch:AI&DS")
print("Current date and time is:", current_time)
#(Above program code should be included in each program at the start of program code)
cstr='*'
print(cstr.ljust(70,'*'))
# Python List
#Create a Python List
# a list of three elements
ages = [19, 26, 29]
print(ages)
Output:
[19, 26, 29]
#List Items of Different Types
# a list containing strings, numbers and another list
student = ['Jack', 32, 'Computer Science', [2, 4]]
print(student)
# an empty list
empty_list = []
print(empty_list)
Output:
['Jack', 32, 'Computer Science', [2, 4]]
#Access List Elements
languages = ['Python', 'Swift', 'C++']
# access the first element
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 59
print('languages[0] =', languages[0])
# access the third element
print('languages[2] =', languages[2])
Output
languages[0] = Python
languages[2] = C++
#Negative Indexing
languages = ['Python', 'Swift', 'C++']
# access the last item
print('languages[-1] =', languages[-1])
# access the third last item
print('languages[-3] =', languages[-3])
Output:
languages[-1] = C++
languages[-3] = Python
#Add Elements to a Python List
fruits = ['apple', 'banana', 'orange']
print('Original List:', fruits)
fruits.append('cherry')
print('Updated List:', fruits)
Output:
Original List: ['apple', 'banana', 'orange']
Updated List: ['apple', 'banana', 'orange', 'cherry']
#Add Elements at the Specified Index
fruits = ['apple', 'banana', 'orange']
print("Original List:", fruits)
fruits.insert(2, 'cherry')
print("Updated List:", fruits)
Output:
Original List: ['apple', 'banana', 'orange']
Updated List: ['apple', 'banana', 'cherry', 'orange']
#Add Elements to a List From Other Iterables
numbers = [1, 3, 5]
print('Numbers:', numbers)
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 60
even_numbers = [2, 4, 6]
print('Even numbers:', numbers)
# adding elements of one list to another
numbers.extend(even_numbers)
print('Updated Numbers:', numbers)
Output:
Numbers: [1, 3, 5]
Even numbers: [2, 4, 6]
Updated Numbers: [1, 3, 5, 2, 4, 6]
#Change List Items (Update List)
colors = ['Red', 'Black', 'Green']
print('Original List:', colors)
# change the first item to 'Purple'
colors[2] = 'Purple'
# change the third item to 'Blue'
colors[2] = 'Blue'
print('Updated List:', colors)
Output:
Original List: ['Red', 'Black', 'Green']
Updated List: ['Purple', 'Black', 'Blue']
#Remove an Item From a List
numbers = [2,4,7,9]
# remove 4 from the list
numbers.remove(4)
print(numbers)
Output:
[2, 7, 9]
#Remove One or More Elements of a List
names = ['John', 'Eva', 'Laura', 'Nick', 'Jack']
# delete the item at index 1
del names[1]
print(names)
# delete items from index 1 to index 2
del names[1: 3]
print(names)
# delete the entire list
del names
# Error! List doesn't exist.
print(names)
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 61
Output:
['John', 'Laura', 'Nick', 'Jack']
['John', 'Jack']
Traceback (most recent call last):
File "", line 15, in
NameError: name 'names' is not defined
#Slicing of a List in Python
my_list = ['p', 'r', 'o', 'g', 'r', 'a', 'm']
print("my_list =", my_list)
# get a list with items from index 2 to index 4 (index 5 is not included)
print("my_list[2: 5] =", my_list[2: 5])
# get a list with items from index 2 to index -3 (index -2 is not included)
print("my_list[2: -2] =", my_list[2: -2])
# get a list with items from index 0 to index 2 (index 3 is not included)
print("my_list[0: 3] =", my_list[0: 3])
Output:
my_list = ['p', 'r', 'o', 'g', 'r', 'a', 'm']
my_list[2: 5] = ['o', 'g', 'r']
my_list[2: -2] = ['o', 'g', 'r']
my_list[0: 3] = ['p', 'r', 'o']
#Omitting Start and End Indices in Slicing
my_list = ['p', 'r', 'o', 'g', 'r', 'a', 'm']
print("my_list =", my_list)
# get a list with items from index 5 to last
print("my_list[5: ] =", my_list[5: ])
# get a list from the first item to index -5
print("my_list[: -4] =", my_list[: -4])
# omitting both start and end index
# get a list from start to end items
print("my_list[:] =", my_list[:])
Output:
my_list = ['p', 'r', 'o', 'g', 'r', 'a', 'm']
my_list[5: ] = ['a', 'm']
my_list[: -4] = ['p', 'r', 'o']
my_list[:] = ['p', 'r', 'o', 'g', 'r', 'a', 'm']
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 62
# Getting current date and time using now().
# importing datetime module for now()
import datetime
# using now() to get current time
current_time = datetime.datetime.now()
# Printing value of now.
print("Name of student:Pandit Yewale")
print("Roll no:1111 Batch: D1 Branch:AI&DS")
print("Current date and time is:", current_time)
#(Above program code should be included in each program at the start of program code)
#Python Tuple
#Create a Python Tuple
numbers = (1, 2, -5)
print(numbers)
tuple_constructor = tuple(('Jack', 'Maria', 'David'))
print(tuple_constructor)
Output:
(1, 2, -5)
('Jack', 'Maria', 'David')
#Different Types of Python Tuples
#Empty Tuple
# create an empty tuple
empty_tuple = ()
print(empty_tuple)
Output:
()
#Tuple of different data types
# tuple of string types
names = ('James', 'Jack', 'Eva')
print (names)
# tuple of float types
float_values = (1.2, 3.4, 2.1)
print(float_values)
Output:
('James', 'Jack', 'Eva')
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 63
(1.2, 3.4, 2.1)
#Tuple of mixed data types
# tuple including string and integer
mixed_tuple = (2, 'Hello', 'Python')
print(mixed_tuple)
Output:
(2, 'Hello', 'Python')
#Access Tuple Items
#Access Items Using Index
languages = ('Python', 'Swift', 'C++')
# access the first item
print(languages[0]) # Python
# access the third item
print(languages[2]) # C++
Output:
Python
C++
#Tuple Cannot be Modified
cars = ('BMW', 'Tesla', 'Ford', 'Toyota')
# trying to modify a tuple
cars[0] = 'Nissan' # error
print(cars)
Output:
ERROR!
Traceback (most recent call last):
File "<main.py>", line 7
C++
^
SyntaxError: invalid syntax
#Delete Tuples
animals = ('dog', 'cat', 'rat')
# deleting the tuple
del animals
Output:
ERROR!
Traceback (most recent call last):
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 64
File "<main.py>", line 7, in <module>
NameError: name 'animals' is not defined
#Concatenation of Tuples
x = (1, 2, 3, 4)
y = (5, 6, 7, 8)
z = x + y #tuple concatenation
print(z)
Output:
(1, 2, 3, 4, 5, 6, 7, 8)
#Slicing of Tuple
#tuple[start : stop : step]
tu = ("W", "S", "C", "U", "B", "E")
print(tu[::]) #('W', 'S', 'C', 'U', 'B', 'E')
print(tu[0::]) #('W', 'S', 'C', 'U', 'B', 'E')
print(tu[0::1]) #('W', 'S', 'C', 'U', 'B', 'E')
print(tu[2::]) #('C', 'U', 'B', 'E')
print(tu[2:6:]) #('C', 'U', 'B', 'E')
print(tu[2:6:1]) #('C', 'U', 'B', 'E')
print(tu[3:7:2]) #('U', 'E')
print(tu[::-1]) #('E', 'B', 'U', 'C', 'S', 'W')
print(tu[-2:-6:-1]) #('B', 'U', 'C', 'S')
Output:
('W', 'S', 'C', 'U', 'B', 'E')
('W', 'S', 'C', 'U', 'B', 'E')
('W', 'S', 'C', 'U', 'B', 'E')
('C', 'U', 'B', 'E')
('C', 'U', 'B', 'E')
('C', 'U', 'B', 'E')
('U', 'E')
('E', 'B', 'U', 'C', 'S', 'W')
('B', 'U', 'C', 'S')
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 65
#Updating Tuples in Python
tu = ('a', 'b', 'c')
tu[0] = 'p' #will generate error
print(tu)
Output:
ERROR!
Traceback (most recent call last):
File "<main.py>", line 2, in <module>
TypeError: 'tuple' object does not support item assignment
#Deleting a Tuple
tu = ('a', 'b', 'c')
del tu[0]
print(tu)
Output:
ERROR!
Traceback (most recent call last):
File "<main.py>", line 2, in <module>
TypeError: 'tuple' object doesn't support item deletion
Conclusion:
Thus we understood how to develop a Python program to manage a task list using lists and
tuples, including adding, removing, updating, and sorting tasks..
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 66
Experiment no 6
Student Enrollment Manager *:
Aim-Create a Python code to demonstrate the use of sets and perform set operations (union,
intersection, difference) to manage student enrollments in multiple courses / appearing for
multiple entrance exams like CET, JEE, NEET etc.
Requirement: Python 3.13.1
Theory:
Sets in Python:
A Set in Python is used to store a collection of items with the following properties.
1. No duplicate elements. If try to insert the same item again, it overwrites previous one.
2. An unordered collection. When we access all items, they are accessed without any
specific order and we cannot access items using indexes as we do in lists.
3. Internally use hashing that makes set efficient for search, insert and delete operations. It
gives a major advantage over a list for problems with these operations.
4. Mutable, meaning we can add or remove elements after their creation, the individual
elements within the set cannot be changed directly.
Example of Python Sets
s = {10, 50, 20}
print(s)
print(type(s))
Output:
{10, 50, 20}
<class 'set'>
Type Casting with Python Set method
The Python set() method is used for type casting.
# typecasting list to set
s = set(["a", "b", "c"])
print(s)
# Adding element to the set
s.add("d")
print(s)
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 67
Output:
{'a', 'b', 'c'}
{'d', 'a', 'b', 'c'}
Check unique and Immutable with Python Set
Python sets cannot have duplicate values. While you cannot modify the individual elements
directly, you can still add or remove elements from the set.
# Python program to demonstrate that
# a set cannot have duplicate values
# and we cannot change its items
# a set cannot have duplicate values
s = {"Geeks", "for", "Geeks"}
print(s)
# values of a set cannot be changed
s[1] = "Hello"
print(s)
Output:
{'Geeks', 'for'}
TypeError: 'set' object does not support item assignment
The first code explains that the set cannot have a duplicate value. Every item in it is a unique
value.
The second code generates an error because we cannot assign or change a value once the set is
created. We can only add or delete items in the set.
Heterogeneous Element with Python Set
Python sets can store heterogeneous elements in it, i.e., a set can store a mixture of string,
integer, boolean, etcdatatypes.
# Python example demonstrate that a set
# can store heterogeneous elements
s = {"Geeks", "for", 10, 52.7, True}
print(s)
Output:
{True, 'for', 'Geeks', 10, 52.7}
In Python, below quick operands can be used for different operations.
| for union.
& for intersection.
– for difference
^ for symmetric difference
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 68
# Program to perform different set operations
# as we do in mathematics
# sets are define
A = {0, 2, 4, 6, 8};
B = {1, 2, 3, 4, 5};
# union
print("Union :", A | B)
# intersection
print("Intersection :", A & B)
# difference
print("Difference :", A - B)
# symmetric difference
print("Symmetric difference :", A ^ B)
Output:
('Union :', set([0, 1, 2, 3, 4, 5, 6, 8]))
('Intersection :', set([2, 4]))
('Difference :', set([8, 0, 6]))
('Symmetric difference :', set([0, 1, 3, 5, 6, 8]))
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 69
Experiment no 6
Aim-Create a Python code to demonstrate the use of sets and perform set operations (union,
intersection, difference) to manage student enrollments in multiple courses / appearing for
multiple entrance exams like CET, JEE, NEET etc.
Requirement: Python 3.13.1
Program code:
# Create a Python code to demonstrate the use of sets and perform set operations (union,
intersection, difference) to manage student enrollments in multiple courses / appearing for
multiple entrance exams like CET, JEE, NEET etc.
# Getting current date and time using now().
# importing datetime module for now()
import datetime
# using now() to get current time
current_time = datetime.datetime.now()
# Printing value of now.
print("Name of student:Pandit Yewale")
print("Roll no:1111 Batch: D1 Branch:AI&DS")
print("Current date and time is:", current_time)
#(Above program code should be included in each program at the start of program code)
cstr='*'
print(cstr.ljust(70,'*'))
# Program to perform different set operations as we do in mathematics
# sets are define
CET = {0, 2, 4, 6, 8};
JEE = {1, 2, 3, 4, 11};
NEET ={2,4,3,7,9,8};
#Students Enrolled for CET examination only.
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 70
print("Students Enrolled for CET examination :",CET)
#Students Enrolled for JEE examination only.
print("Students Enrolled for JEE examination :",JEE)
#Students Enrolled for NEET examination only.
print("Students Enrolled for NEET examination :",NEET)
# Total Number Of Students Registered For CET,JEE & NEET Examination.
# union
Union=CET | JEE |NEET
print("Total Number Of Students Registered For CET,JEE & NEET Examination All
Together :",Union)
#Common Number Of Students Registered For CET,JEE & NEET Examination
# intersection
Intersection = CET & JEE & NEET
print("Common Number Of Students Registered For CET,JEE & NEET
Examination :",Intersection)
Intersection1 = CET & JEE
print("Common Number Of Students Registered For CET & JEE Examination :",Intersection1)
Intersection2 = CET & NEET
print("Common Number Of Students Registered For CET & NEET
Examination :",Intersection2)
Intersection3 = JEE & NEET
print("Common Number Of Students Registered For JEE & NEET
Examination :",Intersection3)
#Number Of Students Registered For for CET Examination only
# difference
Difference = CET - JEE - NEET
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 71
print(" Number Of Students Registered For CET Examination only :",Difference)
#Number Of Students Registered For for JEE Examination only
# difference
Difference = JEE- NEET-CET
print(" Number Of Students Registered For JEE Examination only :",Difference)
#Number Of Students Registered For for NEET Examination only
# difference
Difference = NEET-CET-JEE
print(" Number Of Students Registered For NEET Examination only :",Difference)
Output:
Conclusion:
Thus we Create a Python code to demonstrate the use of sets and perform set operations to
manage student enrollments in multiple courses / appearing for multiple entrance exams like
CET, JEE, NEET etc.
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 72
Experiment no 7
Student Record Keeper *:
Aim-Write a Python program to create, update, and manipulate a dictionary of student records,
including their grades and attendance.
Requirement: Python 3.13.0
Theory:
Dictionaries in Python-
A Python dictionary is a data structure that stores the value in key: value pairs. Values in a
dictionary can be of any data type and can be duplicated, whereas keys can’t be repeated and
must be immutable.
Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier to
find values.
d = {1: 'pandit', 2: 'marks', 3: 'attendance'}
print(d)
Output
{1: 'pandit', 2: 'marks', 3: 'attendance'}
How to Create a Dictionary
In Python, a dictionary can be created by placing a sequence of elements within
curly {} braces, separated by a ‘comma’.
# create dictionary using { }
d1 = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(d1)
# create dictionary using dict() constructor
d2 = dict(a = "Geeks", b = "for", c = "Geeks")
print(d2)
Output:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
{'a': 'Geeks', 'b': 'for', 'c': 'Geeks'}
Dictionary keys are case sensitive: the same name but different cases of Key will be
treated distinctly.
Keys must be immutable: This means keys can be strings, numbers, or tuples but not
lists.
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 73
Keys must be unique: Duplicate keys are not allowed and any duplicate key will
overwrite the previous value.
Dictionary internally uses Hashing. Hence, operations like search, insert, delete can be
performed in Constant Time.
Accessing Dictionary Items
We can access a value from a dictionary by using the key within square brackets orget()method.
d = { "name": "Alice", 1: "Python", (1, 2): [1,2,4] }
# Access using key
print(d["name"])
# Access using get()
print(d.get("name"))
Output
Alice
Alice
Adding and Updating Dictionary Items
We can add new key-value pairs or update existing keys by using assignment.
d = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
# Adding a new key-value pair
d["age"] = 22
# Updating an existing value
d[1] = "Python dict"
print(d)
Output
{1: 'Python dict', 2: 'For', 3: 'Geeks', 'age': 22}
removing Dictionary Items
We can remove items from dictionary using the following methods:
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 74
del: Removes an item by key.
pop(): Removes an item by key and returns its value.
clear(): Empties the dictionary.
popitem(): Removes and returns the last key-value pair.
d = {1: 'Geeks', 2: 'For', 3: 'Geeks', 'age':22}
# Using del to remove an item
del d["age"]
print(d)
# Using pop() to remove an item and return the value
val = d.pop(1)
print(val)
# Using popitem to removes and returns
# the last key-value pair.
key, val = d.popitem()
print(f"Key: {key}, Value: {val}")
# Clear all items from the dictionary
d.clear()
print(d)
Output
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Geeks
Key: 3, Value: Geeks
{}
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 75
Experiment no 7
Aim-Write a Python program to create, update, and manipulate a dictionary of student records,
including their grades and attendance.
Requirement: Python 3.13.0
Progrtam Code:
# Getting current date and time using now().
# importing datetime module for now()
import datetime
# using now() to get current time
current_time = datetime.datetime.now()
# Printing value of now.
print("Name of student:Pandit Yewale")
print("Roll no:1111 Batch: D1 Branch:AI&DS")
print("Current date and time is:", current_time)
#(Above program code should be included in each program at the start of program code)
# Create an empty dictionary
student_dict = {}
# Function to determine grade based on marks
defcalculate_grade(marks):
if marks >= 85:
return 'A'
elif marks >= 70:
return 'B'
elif marks >= 50:
return 'C'
else:
return 'F'
# Get the number of students
n = int(input("Enter the number of students: "))
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 76
# Iterate over the range of students to collect information
for i in range(n):
roll_number = input("Enter roll number: ")
name = input("Enter name: ")
marks = float(input("Enter marks: "))
attendance = float(input("Enter attendance: "))
grade = calculate_grade(marks) # Calculate grade based on marks
# Add the student details to the dictionary
student_dict[roll_number] = {'name': name, 'marks': marks, 'attendance': attendance, 'grade':
grade}
# Display the names of students with marks above 75 and attendance above 75
print("\nStudents with marks above 75 and attendance above 75:")
print("-" * 60)
print(f"{'Name':<20} {'Marks':<10} {'Attendance':<10} {'Grade':<10}")
print("-" * 60)
for roll_number, student in student_dict.items():
if student['marks'] > 75 and student['attendance'] > 75:
print(f"{student['name']:<20} {student['marks']:<10} {student['attendance']:<10}
{student['grade']:<10}")
print("-" * 60)
# Updating student details
update_roll = input("\nEnter the roll number of the student to update: ")
if update_roll in student_dict:
# Update student's marks and attendance
new_marks = float(input(f"Enter new marks for {student_dict[update_roll]['name']}: "))
new_attendance = float(input(f"Enter new attendance for {student_dict[update_roll]['name']}: "))
new_grade = calculate_grade(new_marks) # Recalculate grade based on new marks
# Update the dictionary
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 77
student_dict[update_roll]['marks'] = new_marks
student_dict[update_roll]['attendance'] = new_attendance
student_dict[update_roll]['grade'] = new_grade
print(f"\nUpdated details for {student_dict[update_roll]['name']}:")
print(f"Marks: {new_marks}, Attendance: {new_attendance}, Grade: {new_grade}")
else:
print("Student with this roll number does not exist.")
# Display all student records, including the updated ones in a table format
print("\nAll Student Records (Updated):")
print("-" * 70)
print(f"{'Roll Number':<15} {'Name':<20} {'Marks':<10} {'Attendance':<10} {'Grade':<10}")
print("-" * 70)
for roll_number, student in student_dict.items():
print(f"{roll_number:<15} {student['name']:<20} {student['marks']:<10}
{student['attendance']:<10} {student['grade']:<10}")
print("-" * 70)
Out put:
Enter the number of students: 2
Enter roll number: 1
Enter name: pandit
Enter marks: 85
Enter attendance: 89
Enter roll number: 2
Enter name: sachin
Enter marks: 78
Enter attendance: 76
Students with marks above 75 and attendance above 75:
------------------------------------------------------------
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 78
Name Marks Attendance Grade
------------------------------------------------------------
pandit 85.0 89.0 A
sachin 78.0 76.0 B
------------------------------------------------------------
Enter the roll number of the student to update: 2
Enter new marks for sachin: 80
Enter new attendance for sachin: 79
Updated details for sachin:
Marks: 80.0, Attendance: 79.0, Grade: B
All Student Records (Updated):
----------------------------------------------------------------------
Roll Number Name Marks Attendance Grade
----------------------------------------------------------------------
1 pandit 85.0 89.0 A
2 sachin 80.0 79.0 B
----------------------------------------------------------------------
=== Code Execution Successful ===
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 79
Objective:
To enable students to transition their
understanding of control statements and loops
from C to Python, emphasizing the adoption of
Python syntax while reinforcing logical
structures already learned.
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 80
Experiment no 8
Number Type Identifier*:
Aim-Develop a Python program that takes a numerical input and identifies whether it is even or
odd, utilizing conditional statements and loops.
Requirement: Python 3.13.0
Progrtam Code:
# Getting current date and time using now().
# importing datetime module for now()
import datetime
# using now() to get current time
current_time = datetime.datetime.now()
# Printing value of now.
print("Name of student:Pandit Yewale")
print("Roll no:1111 Batch: D1 Branch:AI&DS")
print("Current date and time is:", current_time)
#(Above program code should be included in each program at the start of program code)
# Python program to check if the input number is odd or even.
# A number is even if division by 2 gives a remainder of 0.
# If the remainder is 1, it is an odd number.
for i in range(2): # Loop will run 5 times
# Taking input from the user
number = int(input("Enter a number: "))
# Checking if the number is even or odd
if number % 2 == 0:
print(f"{number} is even.")
else:
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 81
print(f"{number} is odd.")
# Ask if the user wants to check another number
cont = input("Do you want to check another number? (yes/no): ")
if cont != 'yes':
print("Goodbye!")
break # Exit the loop if the answer is not "yes"
Output:
Conclusion:
Thus we developed a Python program that takes a numerical input and identifies whether it is
even or odd, utilizing conditional statements and loops.
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 82
Experiment no 9
Factorial Generator*:
Aim-Design a Python program to compute the factorial of a given integer N.
Requirement: Python 3.13.0
Progrtam Code:
# Getting current date and time using now().
# importing datetime module for now()
import datetime
# using now() to get current time
current_time = datetime.datetime.now()
# Printing value of now.
print("Name of student:Pandit Yewale")
print("Roll no:1111 Batch: D1 Branch:AI&DS")
print("Current date and time is:", current_time)
# Input: An integer number
num =int(input("Enter the number: "))
# Initialize the factorial variable to 1
factorial = 1
# Calculate the factorial using a for loop
for i in range(1, num + 1):
factorial *= i
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 83
# Output: The factorial of the number
print(f"The factorial of {num} is {factorial}")
Output:
Conclusion:
Thus we design a Python program to compute the factorial of a given integer N.
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 84
Experiment no 10
Prime Number Analyzer*:
Aim-Using function, write a Python program to analyze the input number is prime or not.
Requirement: Python 3.13.0
Progrtam Code:
# Getting current date and time using now().
# importing datetime module for now()
import datetime
# using now() to get current time
current_time = datetime.datetime.now()
# Printing value of now.
print("Name of student:Pandit Yewale")
print("Roll no:1111 Batch: D1 Branch:AI&DS")
print("Current date and time is:", current_time)
def is_prime(number):
# Handle edge case for numbers less than 2
if number < 2:
return False
# Check for factors from 2 to the square root of the number
for i in range(2, int(number ** 0.5) + 1):
if number % i == 0:
return False
return True
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 85
# Take input from the user
num = int(input("Enter a number to check if it is prime: "))
# Call the is_prime function and print the result
if is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")
Output:
Conclusion:
Thus we Used function and write a Python program to analyze the input number is prime or not.
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 86
Experiment no 11
Simple Calculator Using Functions*:
Aim-Implement a simple Python calculator that takes user input and performs basic arithmetic
operations (addition, subtraction, multiplication, division) using functions.
Requirement: Python 3.13.0
Progrtam Code:
# Getting current date and time using now().
# importing datetime module for now()
import datetime
# using now() to get current time
current_time = datetime.datetime.now()
# Printing value of now.
print("Name of student:Pandit Yewale")
print("Roll no:1111 Batch: D1 Branch:AI&DS")
print("Current date and time is:", current_time)
# Python program for simple calculator
# Function to add two numbers
def add(num1, num2):
return num1 + num2
# Function to subtract two numbers
def subtract(num1, num2):
return num1 - num2
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 87
# Function to multiply two numbers
def multiply(num1, num2):
return num1 * num2
# Function to divide two numbers
def divide(num1, num2):
return num1 / num2
print("Please select operation -\n" \
"1. Add\n" \
"2. Subtract\n" \
"3. Multiply\n" \
"4. Divide\n")
n=5
for i in range(n):
# Take input from the user
select = int(input("Select operations form 1, 2, 3, 4 :"))
if select == 1:
number_1 = int(input("Enter first number: "))
number_2 = int(input("Enter second number: "))
print(number_1, "+", number_2, "=",
add(number_1, number_2))
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 88
elif select == 2:
number_1 = int(input("Enter first number: "))
number_2 = int(input("Enter second number: "))
print(number_1, "-", number_2, "=",
subtract(number_1, number_2))
elif select == 3:
number_1 = int(input("Enter first number: "))
number_2 = int(input("Enter second number: "))
print(number_1, "*", number_2, "=",
multiply(number_1, number_2))
elif select == 4:
number_1 = int(input("Enter first number: "))
number_2 = int(input("Enter second number: "))
print(number_1, "/", number_2, "=",
divide(number_1, number_2))
else:
print("Invalid input")
print("program Ended")
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 89
Output:
Conclusion:
Thus we Implement a simple Python calculator that takes user input and performs basic
arithmetic operations (addition, subtraction, multiplication, division) using functions
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 90
Objective: To enable learners to
proficiently handle file operations,
manage exceptions, and create Python
packages and executable files.
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 91
Experiment no 12
Extracting Words from Text File *:
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.
Requirement: Python 3.13.0
Progrtam Code:
# Python program to read
# file word by word
# opening the text file
with open('abcd.txt','r') as file:
# reading each line
for line in file:
#count_word=4
# reading each word
for word in line.split():
#if len(word)==count_word:
# displaying the words
print(word)
Output:
Conclusion:
Thus we 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.
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 92
Experiment no 13
Building an Executable File*:
Aim-Create a executable file for any program developed in earlier practical.
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 93
Objective: To enable learners to
proficiently handle errors and exceptions
in Python programs, ensuring robust and
fault-tolerant code. Learners will also
develop debugging skills to identify,
diagnose, and fix issues efficiently using
scientific debugging methods.
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 94
Experiment no 14
Basic Exception Handling*:
Aim-Write a Python program that takes two numbers as input and performs division. Implement
exception handling to manage division by zero and invalid input errors gracefully.
Requirement: Python 3.13.0
Progrtam Code:
# Example of an exception
for i in range(5):
try:
num1 = int(input("Enter First Number: "))
num2 = int(input("Enter Second Number: "))
result = num1 / num2
print(result)
except ValueError as e:
print("Invalid Input Please Input Integer...")
except ZeroDivisionError as e:
print(e)
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 95
Output:
Conclusion:
Thus we write a Python program that takes two numbers as input and performs division.
Implement exception handling to manage division by zero and invalid input errors gracefully.
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 96
Experiment no 15
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.
Debugging in Python is facilitated by pdb module (python debugger) which comes built-in to
the Python standard library. It is actually defined as the class Pdb which internally makes use of
bdb(basic debugger functions) and cmd (support for line-oriented command interpreters)
modules. The major advantage of pdb is it runs purely in the command line, thereby making it
great for debugging code on remote servers when we don’t have the privilege of a GUI-based
debugger.
pdb supports:
Setting breakpoints
Stepping through code
Source code listing
Viewing stack traces
Starting Python Debugger
There are several ways to invoke a debugger
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.
Example1: Debugging a Simple Python program of addition of numbers using Python pdb
module
Intentional error: As input() returns string, the program cannot use multiplication on strings.
Thus, it’ll raise ValueError.
import pdb
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 97
def addition(a, b):
answer = a * b
return answer
pdb.set_trace()
x = input("Enter first number : ")
y = input("Enter second number : ")
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 :
Command Function
help To display all commands
where Display the stack trace and line number of the current line
next Execute the current line and move to the next line ignoring function calls
step Step into functions called at the current line
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 98
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.
Example 2: Checking variable type using pdb ‘whatis’ command
We can use ‘whatis‘ keyword followed by a variable name (locally or globally defined) to find
its type.
a = 20
b = 10
s=0
for i in range(a):
# this line will raise ZeroDivision error
s += a / b
b -= 1
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 99
From the Command Line: It is the easiest way of using a debugger. You just have to
run the following command in terminal
python -m pdb exppdb.py (put your file name instead of exppdb.py)
This statement loads your source code and stops execution on the first line of code.
Example 3: Navigating in pdb prompt
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
Output :
Example 4: Post-mortem debugging using Python pdb module
Post-mortem debugging means entering debug mode after the program is finished with the
execution process (failure has already occurred). pdb supports post-mortem debugging
through the pm() and post_mortem() functions. These functions look for active trace back and
start the debugger at the line in the call stack where the exception occurred. In the output of the
given example, you can notice pdb appear when an exception is encountered in the program.
def multiply(a, b):
answer = a * b
return answer
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 100
x = input("Enter first number : ")
y = input("Enter second number : ")
result = multiply(x, y)
print(result)
Output :
Checking variables on the Stack
All the variables including variables local to the function being executed in the program as
well as global are maintained on the stack. We can use args(or use a) to print all the arguments
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 101
of a function which is currently active. p command evaluates an expression given as an
argument and prints the result.
Here, example 4 of this article is executed in debugging mode to show you how to check for
variables :
Python pdb Breakpoints
While working with large programs, we often want to add a number of breakpoints where we
know errors might occur. To do this you just have to use the break command. When you insert
a breakpoint, the debugger assigns a number to it starting from 1. Use the break to display all
the breakpoints in the program.
Syntax:
break filename: lineno, condition
Given below is the implementation to add breakpoints in a program used for example 4.
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.
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 102
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 103
Objective: To apply object-oriented
programming (OOP) principles in Python to
model real-world scenarios and systems,
fostering the development of modular,
reusable, and efficient solutions. Fostering
the ability to design and implement solutions
for real-world problems.
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 104
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,
description, stock). You may also want to include categories or tags to help organize your
products.
classProduct:
def__init__(self, name, price, description, stock):
self.name = name
self.price = price
self.description = description
self.stock = stock
defupdate_stock(self, quantity):
self.stock += quantity
deftotal_value(self):
returnself.stock * self.price
2. Created a Product class to represent the different products in the store. The Product class should
have attributes to store the product's name, price, description, stock, and any other relevant
information. It should also have methods to update the stock (e.g. when a product is sold or
restocked), and to calculate the total value of the product in the store (i.e. stock x price).
classOrder:
def__init__(self, customer, product, quantity):
self.customer = customer
self.product = product
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 105
self.quantity = quantity
deftotal_cost(self):
returnself.quantity * self.product.price
3. Created an Order class to represent the orders placed by customers. The Order class should
have attributes to store the customer, the product, and the quantity of the product being ordered. It
should also have a total_cost() method that calculates the total cost of the order.
classCustomer:
def__init__(self, name, email):
self.name = name
self.email = email
self.orders = []
defplace_order(self, product, quantity):
ifproduct.stock>= quantity:
order = Order(self, product, quantity)
product.update_stock(-quantity)
self.orders.append(order)
else:
print("Error: Not enough stock")
defview_orders(self):
for order inself.orders:
print(order)
4. Created a Customer class to represent the store's customers. The Customer class should have
attributes to store the customer's name, email address, and any other relevant information. It
should also have a place_order() method that allows the customer to place an order for a product,
and a view_orders() method that allows the customer to view all of their past orders.
classStore:
definit(self):
self.products = []
self.orders = []
self.customers = []
defadd_product(self, product):
self.products.append(product)
defdelete_product(self, product):
self.products.remove(product)
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 106
defadd_customer(self, customer):
self.customers.append(customer)
defdelete_customer(self, customer):
self.customers.remove(customer)
defadd_order(self, order):
self.orders.append(order)
defdelete_order(self, order):
self.orders.remove(order)
deffind_product(self, name):
for product inself.products:
if product.name == name:
return product
returnNone
deffind_customer(self, name):
for customer inself.customers:
if customer.name == name:
return customer
returnNone
defsales_report(self):
total_sales = 0
for order inself.orders:
total_sales += order.total_cost()
returntotal_sales
defrestock_report(self):
low_stock = []
for product inself.products:
ifproduct.stock<10:
low_stock.append(product)
returnlow_stock
So finally you can check your code, test the classes.
# Test the classes
store = Store()
product1 = Product("Keyboard", 49.99, "Wireless keyboard", 100)
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 107
product2 = Product("Mouse", 29.99, "Wireless mouse", 50)
store.add_product(product1)
store.add_product(product2)
customer1 = Customer("John Smith", "john@example.com")
customer2 = Customer("Jane Doe", "jane@example.com")
store.add_customer(customer1)
store.add_customer(customer2)
customer1.place_order(product1, 1)
customer2.place_order(product2, 2)
print("Total sales:", store.sales_report())
print("Low stock:", store.restock_report())
customer1.view_orders()
This code creates a store, adds two products to the store, adds two customers to the store, and then
places two orders. It then prints the total sales for the store and the products with low stock, and
displays the orders placed by customer1.
Actual code:
class Product:
def __init__(self, name, price, description, stock):
self.name = name
self.price = price
self.description = description
self.stock = stock
def update_stock(self, quantity):
self.stock += quantity
def total_value(self):
return self.stock * self.price
class Order:
def __init__(self, customer, product, quantity):
self.customer = customer
self.product = product
self.quantity = quantity
def total_cost(self):
return self.quantity * self.product.price
class Customer:
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 108
def __init__(self, name, email):
self.name = name
self.email = email
self.orders = []
def place_order(self, product, quantity):
if product.stock >= quantity:
order = Order(self, product, quantity)
product.update_stock(-quantity)
self.orders.append(order) # Add order to the customer's orders list
store.add_order(order) # Add order to the store's orders list
else:
print("Error: Not enough stock")
def view_orders(self):
print(f"Orders for {self.name}:")
if not self.orders:
print("No orders placed.")
for order in self.orders:
print(f"Order for {order.product.name} - Quantity: {order.quantity}, Total cost: $
{order.total_cost():.2f}")
class Store:
def __init__(self):
self.products = []
self.orders = []
self.customers = []
def add_product(self, product):
self.products.append(product)
def delete_product(self, product):
self.products.remove(product)
def add_customer(self, customer):
self.customers.append(customer)
def delete_customer(self, customer):
self.customers.remove(customer)
def add_order(self, order):
self.orders.append(order)
def delete_order(self, order):
self.orders.remove(order)
def find_product(self, name):
for product in self.products:
if product.name == name:
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 109
return product
return None
def find_customer(self, name):
for customer in self.customers:
if customer.name == name:
return customer
return None
def sales_report(self):
total_sales = sum(order.total_cost() for order in self.orders) # Summing up total cost of all
orders
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
# Test the classes
store = Store()
product1 = Product("Keyboard", 49.99, "Wireless keyboard", 100)
product2 = Product("Mouse", 29.99, "Wireless mouse", 50)
store.add_product(product1)
store.add_product(product2)
customer1 = Customer("John Smith", "john@example.com")
customer2 = Customer("Jane Doe", "jane@example.com")
store.add_customer(customer1)
store.add_customer(customer2)
# Customers place orders
customer1.place_order(product1, 1)
customer2.place_order(product2, 2)
# Generate reports
print("Total sales: $", store.sales_report()) # Display total sales
print("Low stock:", [product.name for product in store.restock_report()])
# View customer orders
customer1.view_orders()
customer2.view_orders()
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 110
Output:
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 111
Objective: To develop a
graphical user interface (GUI)
application for any use case.
Choose any use case from
below
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 112
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 asillustrated.
Figure-1: A basic GUI featuring text field and various buttons.
Program Code-
#Creating a simple GUI registration form using Tkinter in Python
#import the tkinter module into our code
from tkinter import *
#Creating the object 'base' of the Tk()
base = Tk()
#Using the Geometry method to the form certain dimensions
base.geometry("550x550")
#Using title method to give the title to the window
base.title('Registration form')
#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)
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 113
#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)
enter_1.place(x=240,y=130)
#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 variable 'vars' to store the integer value, which by deault is 0
vars = IntVar()
#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)
#this creates list of countries available in the dropdown list.
list_of_cntry=[ 'India' ,'Canada' , 'US' ,'Germany' ,'UK']
#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)
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 114
#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.
vars2=IntVar()
#Using the Checkbutton widget to create a button and using place() method to set its position.
Checkbutton(basetext="German", variable=vars2).place(x=290, y=330)
#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)
#Calling the mainloop method to execute the entire program.
base.mainloop()
Output:
The output for the aforementioned Simple registration form's code, using Tkinter in Python is
attached below in the form of a screenshot.
Conclusion:
Thus we developed The college admission registration form.
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 115
Objective: To enable learners to effectively
utilize regular expressions in Python for
pattern matching, validation, and data
extraction tasks, enhancing their ability to
process textual data efficiently and
accurately.
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 116
Experiment 18
Script to Validate Phone Number and Email ID *:
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
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("sachin.sharma@gmail.com")
emailValid("johnsnow123@yahoo.co.uk")
emailValid("mathew123@...uk")
emailValid("...@domain.us")
#validation of mobile phone number
import re
def validate_phone_number(regex, phone_number):
match = re.search(regex, phone_number)
if match:
return True
return False
pattern = re.compile(r"(\+\d{1,3})?\s?\(?\d{1,4}\)?[\s.-]?\d{3}[\s.-]?\d{4}")
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 117
test_phone_numbers = [
"+1 (555) 123-4567",
"555-123-4567",
"555 123 4567",
"+44 (0) 20 1234 5678",
"02012345678",
"invalid phone number"
for number in test_phone_numbers:
print(f"{number}: {validate_phone_number(pattern, number)}")
Output:
Conclusion:
Thus we 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
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 118
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
deffind_emails(text):
# List of email patterns to look for
patterns = [r"\S+@\S+"]
for pattern in patterns:
# Compile the pattern
email_regex = re.compile(pattern)
# Find all instances of the pattern in the text
emails = email_regex.findall(text)
# Print each email found
for email in emails:
print(email)
# Example usage
text = "Please send your resumes on Hr@Iwillgetbacktoyou@gmail.com" \
" for any business enquiry please mail us on business@enquiry.com" \
" and writing.geeksforgeeks.org"
find_emails(text)
Output
Hr@Iwillgetbacktoyou@gmail.com
business@enquiry.com
Conclusion:
Thus we 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).
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 119
Objective: To equip learners
with the skills to utilize the
NumPy libraries for efficient
numerical computing.
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 120
Experiment 20
Creating and Manipulating Arrays*:
Aim-Write a Python program to create a 1D, 2D, and 3D NumPy array. Perform basic operations
like reshaping, slicing, and indexing.
#Create a 1-D array containing the values 1,2,3,4,5:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
#Create a 2-D array containing two arrays with the values 1,2,3 and 4,5,6:
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr)
#Create a 3-D array with two 2-D arrays, both containing two arrays with the values 1,2,3 and
4,5,6:
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(arr)
Reshape From 1-D to 2-D
#Convert the following 1-D array with 12 elements into a 2-D array.
#The outermost dimension will have 4 arrays, each with 3 elements:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newarr = arr.reshape(4, 3)
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 121
print(newarr)
Reshape From 1-D to 3-D
#Convert the following 1-D array with 12 elements into a 3-D array.
#The outermost dimension will have 2 arrays that contains 3 arrays, each with 2 elements:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newarr = arr.reshape(2, 3, 2)
print(newarr)
#Slice elements from index 1 to index 5 from the following array:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[1:5])
#Slice elements from index 4 to the end of the array:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[4:])
#Slice from the index 3 from the end to index 1 from the end:
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 122
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
print(arr[-3:-1])
Array Indexing
#Get the first element from the following array:
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr[0])
#Get the second element from the following array.
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr[1])
#Get third and fourth elements from the following array and add them.
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr[2] + arr[3])
#Access the element on the first row, second column:
import numpy as np
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 123
print('2nd element on 1st row: ', arr[0, 1])
#Access the element on the 2nd row, 5th column:
import numpy as np
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print('5th element on 2nd row: ', arr[1, 4])
#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])
Negative Indexing
#Print the last element from the 2nd dim:
import numpy as np
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print('Last element from 2nd dim: ', arr[1, -1])
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 124
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
# Displaying a message for addition operation
print("Add:")
# Performing addition
print(np.add(1.0, 4.0))
# Displaying a message for subtraction operation
print("Subtract:")
# Performing subtraction
print(np.subtract(1.0, 4.0))
# Displaying a message for multiplication operation
print("Multiply:")
# Performing multiplication
print(np.multiply(1.0, 4.0))
# Displaying a message for division operation
print("Divide:")
# Performing division
print(np.divide(1.0, 4.0))
Sample Output:
Add:
5.0
Subtract:
-3.0
Multiply:
4.0
Divide:
0.25
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 125
# Python Program illustrating
# dot product of two vectors
# Importing numpy module
import numpy as np
# Taking two scalar values
a=5
b=7
# Calculating dot product using dot()
print(np.dot(a, b))
Output:
35
# Python Program illustrating
# dot product of two vectors
# Importing numpy module
import numpy as np
# Taking two 1D array
a = 3 + 1j
b = 7 + 6j
# Calculating dot product using dot()
print(np.dot(a, b))
Output:
(15+25j)
# Python Program illustrating
# dot product of two vectors
# Importing numpy module
import numpy as np
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 126
# Taking two 2D array
# For 2-D arrays it is the matrix product
a = [[2, 1], [0, 3]]
b = [[1, 1], [3, 2]]
# Calculating dot product using dot()
print(np.dot(a, b))
Output:
[[5 4]
[9 6]]
# Python Program illustrating
# dot product of two vectors
# Importing numpy module
import numpy as np
# Taking two 2D array
# For 2-D arrays it is the matrix product
a = [[2, 1], [0, 3]]
b = [[1, 1], [3, 2]]
# Calculating dot product using dot()
# Note that here I have taken dot(b, a)
# Instead of dot(a, b) and we are going to
# get a different output for the same vector value
print(np.dot(b, a))
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 127
Output:
[[2 4]
[6 9]]
# Python3 implementation for dot product
# and cross product of two vector.
n=3
# Function that return
# dot product of two vector array.
defdotProduct(vect_A, vect_B):
product = 0
# Loop for calculate dot product
for i in range(0, n):
product = product + vect_A[i] * vect_B[i]
return product
# Function to find
# cross product of two vector array.
defcrossProduct(vect_A, vect_B, cross_P):
cross_P.append(vect_A[1] * vect_B[2] - vect_A[2] * vect_B[1])
cross_P.append(vect_A[2] * vect_B[0] - vect_A[0] * vect_B[2])
cross_P.append(vect_A[0] * vect_B[1] - vect_A[1] * vect_B[0])
# Driver function
if __name__=='__main__':
vect_A = [3, -5, 4]
vect_B = [2, 6, 5]
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 128
cross_P = []
# dotProduct function call
print("Dot product:", end =" ")
print(dotProduct(vect_A, vect_B))
# crossProduct function call
print("Cross product:", end =" ")
crossProduct(vect_A, vect_B, cross_P)
# Loop that print
# cross product of two vector array.
for i in range(0, n):
print(cross_P[i], end =" ")
Output
Dot product:-4
Cross product:-49 -7 28
Conclusion:
Thus we 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 Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 129
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
Method 1: Using numpy.mean(), numpy.std(), numpy.var()
# Original array
array = np.arange(10)
print(array)
r1 = np.mean(array)
print("\nMean: ", r1)
r2 = np.std(array)
print("\nstd: ", r2)
r3 = np.var(array)
print("\nvariance: ", r3)
Method 2: Using the formulas
import numpy as np
# Original array
array = np.arange(10)
print(array)
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 130
r1 = np.average(array)
print("\nMean: ", r1)
r2 = np.sqrt(np.mean((array - np.mean(array)) ** 2))
print("\nstd: ", r2)
r3 = np.mean((array - np.mean(array)) ** 2)
print("\nvariance: ", r3)
Example: Comparing both inbuilt methods and formulas
import numpy as np
# Original array
x = np.arange(5)
print(x)
r11 = np.mean(x)
r12 = np.average(x)
print("\nMean: ", r11, r12)
r21 = np.std(x)
r22 = np.sqrt(np.mean((x - np.mean(x)) ** 2))
print("\nstd: ", r21, r22)
r31 = np.var(x)
r32 = np.mean((x - np.mean(x)) ** 2)
print("\nvariance: ", r31, r32)
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 131
Objective: To provide learners with the knowledge and
skills necessary to effectively use the Pandas library for
data manipulation and the Matplotlib library for data
visualization. Learners will engage in tasks that involve
analyzing real-world datasets, creating meaningful
visualizations, and drawing insights from data.
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 132
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.
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 133