Latest Lab Manual_Python Programming_6-2-2025
Latest Lab Manual_Python Programming_6-2-2025
Lab Manual
Prepared by –Prof.P.T.Yewale
Lab Outcomes
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
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.
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.
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
Prof.PanditT.Yewale Dr.M.S.Selokar
Subject teacher Head of Department
Practical Batch:
Practical No.:
Aim:
Date of Performance: -
Experiment no 1
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.
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:
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:
Aim-Write a python program to calculate areas of any geometric figures like circle, rectangle ,
triangle, square and Parallelogram
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 = (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
s = (float)(a+b+c)/2;
area = (float)(sqrt(s*(s-a)*(s-b)*(s-c)));
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
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 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)
Conclusion:
Thus we understood how to write a python program to calculate areas of any geometric figures
like circle, rectangle and triangle.
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.
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
We will use the following formulas to calculate house rent allowance (HRA) as 10% of BS
HRA = 0.1*float(BS)
TA = 0.3*float(BS)
We will use the following formulas to calculate provident fund (PF) as 10% of BS
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
Step 1:
Inputs:
Step 2:
Step 3:
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:
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.
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)
import math
Conclusion:
Thus we understood how to write a Python program to calculate the gross salary of an employee.
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.
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
Algorithm:
Step 3:Subtraction operation using - operator, num1 - num2 right hand operand from left
hand operand.
Step 5:Division operation using / operator, num1 / num2 divides left hand operand by right
hand operand.
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
Algorithm:-
Flow Chart:
Flowchart Steps:
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.
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,'*'))
print("1.Addition: ")
print("2.Substration: ")
print("3.Multiplaction: ")
print("4.Division: ")
print("6.Exponent: ")
print("7.Modulus: ")
Conclusion:
Thus we understood how to write a Python program to explore basic arithmetic operations.
Aim- Develop a Python program to manage a task list using lists and tuples, including adding,
removing, updating, and sorting tasks.
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]]
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.
Output:
languages[0] = Python
languages[2] = C++
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.
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
# 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']
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,
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']
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']
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)
Output:
Original List: ['apple', 'banana', 'orange']
Updated List: ['apple', 'banana', 'cherry', 'orange']
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]
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'
Output:
Original List: ['Red', 'Black', 'Green']
Updated List: ['Purple', 'Black', 'Blue']
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']
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
Output:
apple
banana
orange
Python has many useful list methods that make it really easy to work with lists.
Method Description
extend() Adds items of lists and other iterables to the end of the list
Experiment no 5
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 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)
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:
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.
Output:
('Jack', 'Maria', 'David')
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)
Output:
Python
C++
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
Output:
False
True
Here,
For example,
Output:
TypeError: 'tuple' object does not support item assignment
For example,
animals = ('dog', 'cat', 'rat')
# deleting the tuple
del animals
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',)
Flow chart:
cstr='*'
print(cstr.ljust(70,'*'))
# Python List
Output:
['Jack', 32, 'Computer Science', [2, 4]]
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
Output:
Original List: ['apple', 'banana', 'orange']
Updated List: ['apple', 'banana', 'orange', 'cherry']
Output:
Original List: ['apple', 'banana', 'orange']
Updated List: ['apple', 'banana', 'cherry', 'orange']
Output:
Numbers: [1, 3, 5]
Even numbers: [2, 4, 6]
Updated Numbers: [1, 3, 5, 2, 4, 6]
# 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']
Output:
my_list = ['p', 'r', 'o', 'g', 'r', 'a', 'm']
my_list[5: ] = ['a', 'm']
my_list[: -4] = ['p', 'r', 'o']
my_list[:] = ['p', 'r', 'o', 'g', 'r', 'a', 'm']
#Python Tuple
Output:
(1, 2, -5)
('Jack', 'Maria', 'David')
Output:
()
Output:
('James', 'Jack', 'Eva')
(1.2, 3.4, 2.1)
Output:
Python
C++
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
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
#Deleting a Tuple
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..
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.
Output:
{10, 50, 20}
<class 'set'>
Output:
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.
Output:
{True, 'for', 'Geeks', 10, 52.7}
# 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]))
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.
+------------------+
| Start |
+------------------+
+-------------------------------+
+-------------------------------+
+---------------------------------+
| Exam Separately |
+---------------------------------+
+--------------------------------+
+--------------------------------+
+--------------------------------------+
+--------------------------------------+
+-------------------------------+
+-------------------------------+
+-------------------------------+
+-------------------------------+
+------------------+
| End |
+------------------+
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.
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.
print(cstr.ljust(70,'*'))
NEET ={2,4,3,7,9,8};
# union
print("Total Number Of Students Registered For CET,JEE & NEET Examination All
Together :",Union)
# intersection
# difference
# difference
# difference
Difference = NEET-CET-JEE
Output:
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
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
print(d1)
print(d2)
Output:
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.
We can access a value from a dictionary by using the key within square brackets orget()method.
print(d["name"])
print(d.get("name"))
We can add new key-value pairs or update existing keys by using assignment.
d["age"] = 22
print(d)
Output
del d["age"]
print(d)
val = d.pop(1)
print(val)
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.
Progrtam Code:
# 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)
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
# 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():
Out put:
Flow chart:
Initialize student_dict
Define calculate_grade()
┌──────────────────────────┐
│ Loop (i = 0 to n-1) │
├──────────────────────────┤
│ Calculate grade │
│ Store in student_dict │
└──────────────────────────┘
┌──────────────┬───────────────┐
│ Yes │ No │
▼ ▼ ▼
new attendance
Recalculate grade
Update student_dict
Conclusion:
Thus we create a Python program to create, update, and manipulate a dictionary of student
records, including their grades and attendance.
Experiment no 8
Theory:
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.
Algorithms:
Start
Repeat the following steps until the user decides to stop:
End
Flow Chart:
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 90
: ┌────────── Start ──────────┐
│ │
▼ │
┌─────────────────┐ │
│ Input number │
└─────────────────┘
┌───────────────────────┐
│ Is number % 2 == 0? │
└───────────────────────┘
/ \
Yes No
▼ ▼
┌─────────────────┐ ┌─────────────────┐
└─────────────────┘ └─────────────────┘
┌───────────────────────┐
└───────────────────────┘
┌───────────────────────┐
└───────────────────────┘
/ \
Yes No
▼ ▼
│ "Goodbye!"│
└───────────┘
**End**
Progrtam Code:
while True: # Infinite loop, will break when user says "no"
if number % 2 == 0:
print(f"{number} is even.")
else:
print(f"{number} is odd.")
if cont != 'yes': # If user input is anything other than "yes", exit loop
print("Goodbye!")
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.
Factorial Generator*:
Aim-Design a Python program to compute the factorial of a given integer N.
Theory:
Factorial of a positive integer (number) is the sum of multiplication of all the integers smaller
than that positive integer.
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.
Factorial Generator*:
Aim-Design a Python program to compute the factorial of a given integer N.
Algorithm:
Start
Loop until the user chooses to exit:
End
Start
Enter a number
(num)
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
while True:
if num < 0:
continue
factorial = 1
factorial *= i
print("Goodbye!")
break
Output:
Conclusion:
Experiment no 10
Theory:
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
Algorithm:
1. Start
Flowchart:
+------------------+
| Start |
+------------------+
+-----------------------+
+-----------------------+
+---------------------------+
| Is num < 2? |
+---------------------------+
| Yes | No
v v
+-----------------+ +--------------------------+
+-----------------+ +--------------------------+
| v
| +-------------------------+
| | Check if num % i == 0 |
| +-------------------------+
| |
| Yes | No
| v v
| +-----------------+ |
| | Return False | |
| | (Not Prime) | |
| +-----------------+ |
| |
| v
| +---------------------+
| | Increment i by 1 |
| +---------------------+
| |
| v
| |
| v
| +-----------------+
| | Return True |
| | (Number is Prime)|
| +-----------------+
v v
+-----------------+ +----------------+
+-----------------+ +----------------+
Program code:
defis_prime(number):
if number < 2:
return False
if number % i == 0:
return False
return True
if is_prime(num):
else:
Output:
Experiment no 11
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
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 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:
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
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
Algorithm:
Start
Display menu options for operations:
2. Subtract
3. Multiply
4. Divide
Flow chart:
+------------------+
| Start |
+------------------+
+------------------------------------+
| 1. Add 2. Subtract |
| 3. Multiply 4. Divide |
+------------------------------------+
+-------------------------------+
+-------------------------------+
+----------------------------------+
+----------------------------------+
+------------------------------------+
+------------------------------------+
| | | |
v v v v
| | | |
v v v v
| |
| v
| Is num2 = 0?
| Yes | No
| v v
| Display error
+----------------------------------+
+----------------------------------+
+----------------------------------+
+----------------------------------+
| Yes | No
v v
+----------------+ +------------------+
+----------------+ +------------------+
"1. Add\n" \
"2. Subtract\n" \
"3. Multiply\n" \
"4. Divide\n")
if select == 1:
add(number_1, number_2))
elif select == 2:
subtract(number_1, number_2))
elif select == 3:
multiply(number_1, number_2))
elif select == 4:
divide(number_1, number_2))
else:
print("Invalid input")
Output: