0% found this document useful (0 votes)
7 views

Latest Lab Manual_Python Programming_6-2-2025

The document is a lab manual for the Python Programming course at A.C. Patil College of Engineering, detailing lab outcomes, program outcomes, and a list of experiments for students. It outlines the skills students will develop, such as proficiency in Python programming, control flow, file operations, and GUI design. Additionally, it includes evaluation criteria and a sample experiment for generating personalized greetings using Python.

Uploaded by

Shaikh Rafee
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Latest Lab Manual_Python Programming_6-2-2025

The document is a lab manual for the Python Programming course at A.C. Patil College of Engineering, detailing lab outcomes, program outcomes, and a list of experiments for students. It outlines the skills students will develop, such as proficiency in Python programming, control flow, file operations, and GUI design. Additionally, it includes evaluation criteria and a sample experiment for generating personalized greetings using Python.

Uploaded by

Shaikh Rafee
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 111

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.
Expt Experiment name LO PO
no
1 Aim-Write a python code to generate Personalized L1 1,2,3,4,5,7,9,10,11,12
Greeting.
2 Aim-Write a python program to calculate areas of any L1 1,2,3,4,5,7,9,10,11,12
geometric figures like circle, rectangle and triangle.
3 Aim- Write a Python program to calculate the gross L1 1,2,3,4,5,7,9,10,11,12
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, 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,12
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.
5 Aim- Develop a Python program to manage a task list L1 1,2,3,4,5,7,9,10,11,12
using lists and tuples, including adding, removing,
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,12
and perform set operations (union, intersection,
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,12
manipulate a dictionary of student records, including
their 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,12
input and identifies whether it is even or odd, utilizing
conditional statements and loops.
9 Aim-Design a Python program to compute the factorial L2 1,2,3,4,5,7,9,10,11,12
of a given integer N.
10 Aim-Using function, write a Python program to analyze L2 1,2,3,4,5,7,9,10,11,12
the input number is prime or not.
11 Aim-Implement a simple Python calculator that takes L2 1,2,3,4,5,7,9,10,11,12
user input and performs basic arithmetic operations
(addition, 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,12
prints words of specified lengths (e.g., three, four, five,
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,12
in earlier practical.
14 Aim-Write a Python program that takes two numbers as L3 1,2,3,4,5,7,9,10,11,12
input and performs division. Implement exception
handling to manage division by zero and invalid input
errors gracefully.
15 Aim-Demonstrate the use of a Python debugger (e.g., L3 1,2,3,4,5,7,9,10,11,12
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.
16 Aim-Develop classes for products, customers, and L4 1,2,3,4,5,7,9,10,11,12
shopping carts. Include methods for adding items to the
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,12
essential personal, educational, and contact information
from prospective students. Create a GUI as shown in
Figure-1 that allows the user to input his/her name,
branch and favorite game. When the user clicks the
Submit button, it should display the output as illustrated.
18 Aim- Write a Python script that prompts the user to enter L5 1,2,3,4,5,7,9,10,11,12
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
19 Aim- Create a program that reads a text file containing L5 1,2,3,4,5,7,9,10,11,12
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).
20 Aim-Write a Python program to create a 1D, 2D, and 3D L6 1,2,3,4,5,7,9,10,11,12
NumPy array. Perform basic operations like reshaping,
slicing, and indexing.

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 7


21 Aim-Develop a Python script to create two arrays of the L6 1,2,3,4,5,7,9,10,11,12
same shape and perform element-wise addition,
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,12


standard deviation, variance, and correlation coefficients
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)

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: ")
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 13
print(f"{message}",name)

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 14


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

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 15


area = (float)side*side;

 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 16


Flow Chart:

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 17


Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 18
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 19
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 20
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 21


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 22


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 23


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 24


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 25


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 26


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 27


# 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 28


Output:

Conclusion:

Thus we understood how to write a Python program to calculate the gross salary of an employee.

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.

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 29


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
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

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 30


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:

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.

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 31


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:-

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

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 32


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 33


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

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 34


add = num1 + num2

dif = num1 - num2

mul = num1 * num2

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)

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 35


Output:

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 36


Objective:
Mastering Python New Data
Structures for Practical
Applications

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 37


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 38


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 39


# 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 40


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 41


# 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 42


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 43


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 44


# 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 45


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 46


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 = []

def add_item(self, item):


"""Add an item to the list"""
self.items.append(item)
print(f"Item '{item}' added to the list.")

def remove_item(self, item):


"""Remove an item from the list"""
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.")

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 47


def update_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.")

def sort_list(self):
"""Sort the list"""
self.items.sort()
print("List sorted.")

def display_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")
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':
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 48
print("Exiting the program.")
break
else:
print("Invalid choice, please try again.")

if __name__ == "__main__":
main()
Output:

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 49


Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 50
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)

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 51


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
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)

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 52


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

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++

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 53


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 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)

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 54


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
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

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 55


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')
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 56


Algorithm:-

Flow chart:

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 57


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


Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 58
# 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
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

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 59


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)
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']
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 60
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)
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']
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 61
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']

# 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")

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 62


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')
(1.2, 3.4, 2.1)

#Tuple of mixed data types


# tuple including string and integer
mixed_tuple = (2, 'Hello', 'Python')
print(mixed_tuple)

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 63


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):
File "<main.py>", line 7, in <module>
NameError: name 'animals' is not defined

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 64


#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')

#Updating Tuples in Python

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 65


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

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 67


s.add("d")
print(s)

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}

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 68


In Python, below quick operands can be used for different operations.
| for union.
& for intersection.
– for difference
^ for symmetric difference
# 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


Algorithm:-

Algorithm: Perform Set Operations for Examination Enrollment

Step 1: Define Sets

1. Create three sets:


o CET = {0, 2, 4, 6, 8}
o JEE = {1, 2, 3, 4, 11}
o NEET = {2, 4, 3, 7, 9, 8}

Step 2: Display Individual Sets

2. Print the students enrolled in each exam individually.

Step 3: Perform Set Operations

3. Find the total number of students registered (Union of all three sets).
o Union = CET | JEE | NEET
o Print the result.

4. Find students registered for all three exams (Intersection of all three sets).
o Intersection = CET & JEE & NEET
o Print the result.

5. Find students registered for exactly two exams


o Intersection1 = CET & JEE (Students in both CET and JEE).
o Intersection2 = CET & NEET (Students in both CET and NEET).
o Intersection3 = JEE & NEET (Students in both JEE and NEET).
o Print each result.

6. Find students who registered for only one exam


o Difference_CET = CET - JEE - NEET (Students only in CET).
o Difference_JEE = JEE - NEET - CET (Students only in JEE).
o Difference_NEET = NEET - CET - JEE (Students only in NEET).
o Print each result.

Step 4: Display Final Results

7. Print all the computed results.

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 70


Flow chart:

+------------------+

| Start |

+------------------+

+-------------------------------+

| Define sets CET, JEE, NEET |

+-------------------------------+

+---------------------------------+

| Print Students Enrolled in Each|

| Exam Separately |

+---------------------------------+

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 71


v

+--------------------------------+

| Find Union (CET | JEE | NEET) |

+--------------------------------+

+--------------------------------------+

| Find Intersection (CET & JEE & NEET)|

+--------------------------------------+

+-------------------------------+

| Find Pairwise Intersections |

| CET & JEE, CET & NEET, JEE & NEET |

+-------------------------------+

+-------------------------------+

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 72


| Find Students in Only One Exam|

| CET - JEE - NEET |

| JEE - NEET - CET |

| NEET - CET - JEE |

+-------------------------------+

+------------------+

| End |

+------------------+

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 73


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)

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 74


#(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.

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

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 75


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

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:

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 76


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.

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

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 77


{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.

 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"))

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 78


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:

 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)

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 79


# 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
{}

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)

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 80


# Create an empty dictionary
student_dict = {}

# Function to determine grade based on marks


def calculate_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: "))

# 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)
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 81
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


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():

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 82


print(f"{roll_number:<15} {student['name']:<20} {student['marks']:<10}
{student['attendance']:<10} {student['grade']:<10}")
print("-" * 70)

Out put:

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 83


Algorithm:-
 Initialize an empty dictionary student_dict to store student records.
 Define a function calculate_grade(marks):

 If marks ≥ 85, return 'A'.


 Else if marks ≥ 70, return 'B'.
 Else if marks ≥ 50, return 'C'.
 Otherwise, return 'F'.

 Get the number of students (n) as input.


 Loop from 0 to n-1:

 Get roll_number, name, marks, and attendance as input.


 Calculate grade using calculate_grade(marks).
 Store student details in student_dict with roll_number as the key.

 Display students with marks > 75 and attendance > 75:

 Print table headers.


 Iterate over student_dict and check conditions.
 If both conditions are met, print student details.

 Update student details:

 Get update_roll as input.


 If update_roll exists in student_dict:
o Get new_marks and new_attendance.
o Recalculate grade.
o Update student_dict with new values.
o Print updated student details.
 Else, print "Student with this roll number does not exist."

 Display all student records in a table format:

 Print table headers.


 Iterate over student_dict and print all details.

Flow chart:

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 84


Start

Initialize student_dict

Define calculate_grade()

Input number of students (n)

┌──────────────────────────┐

│ Loop (i = 0 to n-1) │

├──────────────────────────┤

│ Input roll_number, name │

│ Input marks, attendance │

│ Calculate grade │

│ Store in student_dict │

└──────────────────────────┘

Check students with marks > 75 and attendance > 75

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 85


Display qualifying students

Input roll_number for update

Does roll_number exist?

┌──────────────┬───────────────┐

│ Yes │ No │

▼ ▼ ▼

Input new marks, Print "Student not found"

new attendance

Recalculate grade

Update student_dict

Display updated student details

Display all student records

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 86


End

Conclusion:
Thus we create a Python program to create, update, and manipulate a dictionary of student
records, including their grades and attendance.

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 87


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.

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

Theory:

Even number and Odd number:

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 88


An "even number" is a number that can be divided exactly by 2, meaning it leaves no remainder
when divided by 2, while an "odd number" is a number that cannot be divided exactly by 2,
leaving a remainder of 1 when divided by 2; essentially, even numbers are divisible by 2, and
odd numbers are not.
Key points about even and odd numbers:
Divisibility by 2: This is the key factor - if a number can be divided by 2 without leaving a
remainder, it is even; if it leaves a remainder of 1 when divided by 2, it is odd.
Examples:
Even numbers: 2, 4, 6, 8, 10, 12
Odd numbers: 1, 3, 5, 7, 9, 11

Identifying by the last digit: You can quickly tell if a number is even or odd by looking at its
last digit - if the last digit is 0, 2, 4, 6, or 8, it is even; if it is 1, 3, 5, 7, or 9, it is odd.

Modulus operator (%): It is arithmetic operator used to check the remainder value when
divisions of two numbers are performed internally.
In programming, the modulus operator (%) is used to determine whether a number is
even or odd by checking if the remainder after dividing the number by 2 is 0 (even) or 1
(odd); essentially, if the result of "number % 2" is 0, the number is even, otherwise it's odd.
Key points about using the modulus operator for even/odd checks:
Modulo operation: The modulus operator (%) returns the remainder of a division operation.
Even number condition: If a number divided by 2 leaves no remainder (i.e., the modulo result
is 0), it is considered even.
Odd number condition: If a number divided by 2 leaves a remainder of 1 (i.e., the modulo
result is 1), it is considered odd.
Example:
Checking if 8 is even:
Calculation: 8 % 2 = 0
Result: Since the remainder is 0, 8 is even.

Checking if 7 is odd:
Calculation: 7 % 2 = 1
Result: Since the remainder is 1, 7 is odd.

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 89


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

Algorithms:

 Start
 Repeat the following steps until the user decides to stop:

1. Prompt the user to enter a number.


2. Convert the input into an integer.
3. If the number is divisible by 2 (i.e., number % 2 == 0):
o Print that the number is even.
4. Else:
o Print that the number is odd.
5. Ask the user if they want to check another number.
6. If the user's input is not "yes", print "Goodbye!" and exit the loop.

 End

Flow Chart:
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 90
: ┌────────── Start ──────────┐

│ │

▼ │

┌─────────────────┐ │

│ Input number │

└─────────────────┘

┌───────────────────────┐

│ Is number % 2 == 0? │

└───────────────────────┘

/ \

Yes No

▼ ▼

┌─────────────────┐ ┌─────────────────┐

│ Print "Even" │ │ Print "Odd" │

└─────────────────┘ └─────────────────┘

┌───────────────────────┐

│ Ask user: "Check another?" │

└───────────────────────┘

┌───────────────────────┐

│ Input: "yes" or "no" │

└───────────────────────┘

/ \

Yes No

▼ ▼

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 91


Repeat ┌───────────┐

│ "Goodbye!"│

└───────────┘

**End**

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)

while True: # Infinite loop, will break when user says "no"

# 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:

print(f"{number} is odd.")

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 92


# Ask if the user wants to check another number

cont = input("Do you want to check another number? (yes/no): ").strip().lower()

if cont != 'yes': # If user input is anything other than "yes", exit loop

print("Goodbye!")

break # Exit the loop

Output:

Conclusion:

Thus we develop 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 93


Experiment no 9

Factorial Generator*:
Aim-Design a Python program to compute the factorial of a given integer N.

Requirement: Python 3.13.0

Theory:

Factorial of a positive integer (number) is the sum of multiplication of all the integers smaller
than that positive integer.

Compute the factorial of an number:

To compute the factorial of an integer N, you multiply that number (N) by every positive integer
less than it, down to 1; mathematically represented as N! = N x (N-1) x (N-2) x ... x 2 x 1; where
"!" denotes the factorial operation.
Example:
To calculate the factorial of 5 (written as 5!), you would multiply 5 x 4 x 3 x 2 x 1, which equals
120.

Key points about factorials:


Notation: The factorial of a number N is written as N!.
Base case: By convention, 0! (factorial of 0) is defined as 1.
Calculation process:
Start with the number N.
Multiply N by the next smaller integer (N-1).
Continue multiplying by each decreasing integer until you reach 1.

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 94


Experiment no 9

Factorial Generator*:
Aim-Design a Python program to compute the factorial of a given integer N.

Requirement: Python 3.13.0

Algorithm:

 Start
 Loop until the user chooses to exit:

1. Prompt the user to enter an integer number.


2. If the number is negative, display an error message and continue.
3. Initialize factorial = 1.
4. Use a for loop to calculate the factorial:
o Iterate from 1 to num.
o Multiply factorial by each number in the loop.
5. Display the calculated factorial.
6. Ask the user if they want to check another number.
7. If the user enters "no" or "n", exit the loop.

 End

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 95


Flowchart:

Start

Enter a number
(num)

Display error YES Is num NO Initialize factorial as 1


negative?
Factorial not defined
for -ve

Loop i from 1 to
num
Multiply
factorial by i

Display
factorial result

Go back to YES
Ask if
input
user
wants to

NO

END

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 96


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)

while True:

num = int(input("Enter the number: "))

if num < 0:

print("Factorial is not defined for negative numbers.")

continue

factorial = 1

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

factorial *= i

print(f"The factorial of {num} is {factorial}")

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 97


# Ask if the user wants to check another number

choice = input("Do you want to check another number? (yes/no): ").strip().lower()

if choice not in ['yes', 'y']:

print("Goodbye!")

break

Output:

Conclusion:

Thus we develop a Python program to compute the factorial of a given integer N.

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

Theory:

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 98


Prime numbers are natural numbers that are divisible by only 1 and the number itself. In other
words, prime numbers are positive integers greater than 1 with exactly two factors, 1 and the
number itself. Some of the prime numbers include 2, 3, 5, 7, 11, 13, etc. Always remember that 1
is neither prime nor composite.

A number is considered "prime" if it is greater than 1 and can only be divided evenly by 1 and
itself; meaning it has only two factors: 1 and the number itself; any number with more than two
factors is considered a "composite" number.
Key points about prime numbers:
Definition: A prime number is a positive integer greater than 1 that is only divisible by 1 and
itself.
Example: The number 7 is prime because it can only be divided by 1 and 7.
Composite numbers: Numbers that have more than two factors are called composite numbers.
Checking for primality: To determine if a number is prime, check if it can be divided evenly by
any number other than 1 and itself.

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

Algorithm:

1. Start

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 99


2. Input the number to check (num).
3. Handle edge cases:
o If num < 2, return False (since prime numbers are ≥ 2).
4. Loop from 2 to √num:
o If num is divisible by any number in this range, return False.
5. If no factors are found, return True (indicating num is prime).
6. Display the result:
o If is_prime(num) returns True, print "num is a prime number."
o Otherwise, print "num is not a prime number."
7. End

Flowchart:

+------------------+

| Start |

+------------------+

+-----------------------+

| Enter a number (num) |

+-----------------------+

+---------------------------+

| Is num < 2? |

+---------------------------+

| Yes | No

v v

+-----------------+ +--------------------------+

| Return False | | Initialize i = 2 |

| (Not Prime) | | Loop till √num |

+-----------------+ +--------------------------+

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 100


| |

| v

| +-------------------------+

| | Check if num % i == 0 |

| +-------------------------+

| |

| Yes | No

| v v

| +-----------------+ |

| | Return False | |

| | (Not Prime) | |

| +-----------------+ |

| |

| v

| +---------------------+

| | Increment i by 1 |

| +---------------------+

| |

| v

| (Loop continues till √num)

| |

| v

| +-----------------+

| | Return True |

| | (Number is Prime)|

| +-----------------+

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 101


| |

v v

+-----------------+ +----------------+

| Print Result | | End |

+-----------------+ +----------------+

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)

defis_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 102


# 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:

Enter a number to check if it is prime: 15

15 is not a prime number.

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

Theory:

This Python code implements a simple calculator that can perform basic arithmetic operations
such as addition, subtraction, multiplication, and division. Let's break it down:

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 103


1. Function Definitions:

 The code defines four functions to handle the arithmetic operations:


o add(num1, num2): Adds two numbers and returns the result.
o subtract(num1, num2): Subtracts num2 from num1 and returns the result.
o multiply(num1, num2): Multiplies two numbers and returns the result.
o divide(num1, num2): Divides num1 by num2 and returns the result.

2. Displaying the Menu:

The program displays a simple menu to the user to choose an operation:

python
CopyEdit
print("Please select operation -\n" \
"1. Add\n" \
"2. Subtract\n" \
"3. Multiply\n" \
"4. Divide\n")

This displays the available operations: add, subtract, multiply, and divide.

3. User Input:

The program then prompts the user to input:

 The operation they want to perform (select), which is an integer between 1 and 4.
 Two numbers (number_1 and number_2) to perform the operation on.

4. Conditional Logic:

The if-elif statements check which operation the user selected:

 If select == 1, it calls the add() function with number_1 and number_2 and prints the
result in the format: number_1 + number_2 = result.
 If select == 2, it calls the subtract() function and prints the result similarly.
 If select == 3, it calls the multiply() function.
 If select == 4, it calls the divide() function.
 If the user enters any other number (not 1, 2, 3, or 4), it prints "Invalid input."

Example Flow:

If the user selects 1 (for addition), and inputs 5 and 3 as the numbers, the program will output:

sql
CopyEdit
Enter first number: 5
Enter second number: 3
5 + 3 = 8

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 104


Error Handling:

 There is no explicit error handling for cases like dividing by zero. If the user inputs 0 as the
second number for division, the program will raise a ZeroDivisionError.

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

Algorithm:

 Start
 Display menu options for operations:

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 105



1. Add

2. Subtract

3. Multiply

4. Divide

 Take user input for operation selection (select).


 Input two numbers (num1 and num2).
 Perform the selected operation:

 If select == 1, call add(num1, num2) and print the result.


 If select == 2, call subtract(num1, num2) and print the result.
 If select == 3, call multiply(num1, num2) and print the result.
 If select == 4, check if num2 is not zero:
o If num2 ≠ 0, call divide(num1, num2) and print the result.
o If num2 == 0, display an error message (Cannot divide by zero).

 If input is invalid, display an error message.


 End

Flow chart:

+------------------+

| Start |

+------------------+

+------------------------------------+

| Display operation menu: |

| 1. Add 2. Subtract |

| 3. Multiply 4. Divide |

+------------------------------------+

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 106


v

+-------------------------------+

| Take user input (select) |

+-------------------------------+

+----------------------------------+

| Take input: num1, num2 |

+----------------------------------+

+------------------------------------+

| Check selected operation (select) |

+------------------------------------+

| | | |

v v v v

(1) (2) (3) (4)

Add Subtract Multiply Divide

| | | |

v v v v

+-------------+ +------------+ +--------------+

| num1 + num2 | | num1 - num2 | | num1 / num2 |

+-------------+ +------------+ +--------------+

| |

| v

| Is num2 = 0?

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 107


| |

| Yes | No

| v v

| Display error

| "Cannot divide by zero"

+----------------------------------+

| Display the result |

+----------------------------------+

+----------------------------------+

| Ask user if they want to repeat |

+----------------------------------+

| Yes | No

v v

+----------------+ +------------------+

| Go back to menu | | End |

+----------------+ +------------------+

# 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 Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 108


#(Above program code should be included in each program at the start of program code)

# 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

# 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")

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 109


# Take input from the user

select = int(input("Select operations form 1, 2, 3, 4 :"))

number_1 = int(input("Enter first number: "))

number_2 = int(input("Enter second number: "))

if select == 1:

print(number_1, "+", number_2, "=",

add(number_1, number_2))

elif select == 2:

print(number_1, "-", number_2, "=",

subtract(number_1, number_2))

elif select == 3:

print(number_1, "*", number_2, "=",

multiply(number_1, number_2))

elif select == 4:

print(number_1, "/", number_2, "=",

divide(number_1, number_2))

else:

print("Invalid input")

Output:

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 110


Please select operation -
1. Add
2. Subtract
3. Multiply
4. Divide

Select operations form 1, 2, 3, 4 :1


Enter first number: 5
Enter second number: 6
5 + 6 = 11

Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 111

You might also like