Pandit _modified Lab Manual _python
Pandit _modified Lab Manual _python
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:
Program Code:
# Getting current date and time using now().
# importing datetime module for now()
import datetime
# using now() to get current time
current_time = datetime.datetime.now()
# Printing value of now.
print("Name of student:Pandit Yewale")
print("Roll no:1111 Batch: D1 Branch:AI&DS")
print("Current date and time is:", current_time)
cstr='*'
print(cstr.ljust(70,'*'))
#(Above program code should be included in each program at the start of program code)
# Python program that asks the user to enter their name, and then greet them.
print("Welcome to the name and greet program!")
name = input("Please enter your name: ")
message=input("Please enter greeting message: ")
print(f"{message}",name)
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)side*side;
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.
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
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.
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
Algorithm:-
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: ")
Output:
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 = []
defadd_item(self, item):
"""Add an item to the list"""
self.items.append(item)
print(f"Item '{item}' added to the list.")
defremove_item(self, item):
"""Remove an item from the list"""
defsort_list(self):
"""Sort the list"""
self.items.sort()
print("List sorted.")
defdisplay_list(self):
"""Display the current list"""
print("Current list:", self.items)
while True:
print("\nMenu:")
print("1. Add item")
print("2. Remove item")
Python Programming Lab Manual Prepared by-Prof.PanditT.Yewale Page 49
print("3. Update item")
print("4. Sort list")
print("5. Display list")
print("6. Exit")
if choice == '1':
item = input("Enter the item to add: ")
manager.add_item(item)
elif choice == '2':
item = input("Enter the item to remove: ")
manager.remove_item(item)
elif choice == '3':
old_item = input("Enter the item to update: ")
new_item = input("Enter the new item: ")
manager.update_item(old_item, new_item)
elif choice == '4':
manager.sort_list()
elif choice == '5':
manager.display_list()
elif choice == '6':
print("Exiting the program.")
break
else:
print("Invalid choice, please try again.")
if __name__ == "__main__":
main()
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:
(1, 2, -5)
Output:
('Jack', 'Maria', 'David')
Empty Tuple
# create an 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
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:
apple
banana
orange
Output:
False
Here,
For example,
Output:
TypeError: 'tuple' object does not support item assignment
Delete Tuples
We cannot delete individual items of a tuple. However, we can delete the tuple itself
using the del statement.
For example,
animals = ('dog', 'cat', 'rat')
# deleting the tuple
del animals
For example,
var = ('Hello')
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',)
cstr='*'
print(cstr.ljust(70,'*'))
# Python List
Output:
['Jack', 32, 'Computer Science', [2, 4]]
#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']
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']
Output:
(1, 2, -5)
('Jack', 'Maria', 'David')
Output:
()
Output:
('James', 'Jack', 'Eva')
Output:
(2, 'Hello', 'Python')
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):
#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
#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:
{'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]))
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
print("Common Number Of Students Registered For CET & JEE Examination :",Intersection1)
# difference
# difference
# difference
Difference = NEET-CET-JEE
Output:
Conclusion:
Thus we Create a Python code to demonstrate the use of sets and perform set operations to
manage student enrollments in multiple courses / appearing for multiple entrance exams like
CET, JEE, NEET etc.
Theory:
Dictionaries in Python-
A Python dictionary is a data structure that stores the value in key: value pairs. Values in a
dictionary can be of any data type and can be duplicated, whereas keys can’t be repeated and
must be immutable.
Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier to
find values.
d = {1: 'pandit', 2: 'marks', 3: 'attendance'}
print(d)
Output
{1: 'pandit', 2: 'marks', 3: 'attendance'}
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.
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"))
Output
Alice
Alice
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
{}
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)
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():
print(f"{roll_number:<15} {student['name']:<20} {student['marks']:<10}
{student['attendance']:<10} {student['grade']:<10}")
print("-" * 70)
Out put:
Enter the number of students: 2
Enter roll number: 1
Enter name: pandit
Enter marks: 85
Enter attendance: 89
Enter roll number: 2
Enter name: sachin
Enter marks: 78
Enter attendance: 76
Progrtam Code:
if number % 2 == 0:
print(f"{number} is even.")
else:
if cont != 'yes':
print("Goodbye!")
Output:
Conclusion:
Thus we developed a Python program that takes a numerical input and identifies whether it is
even or odd, utilizing conditional statements and loops.
Factorial Generator*:
Aim-Design a Python program to compute the factorial of a given integer N.
Progrtam Code:
import datetime
current_time = datetime.datetime.now()
factorial = 1
factorial *= i
Output:
Conclusion:
Thus we design a Python program to compute the factorial of a given integer N.
Progrtam Code:
import datetime
current_time = datetime.datetime.now()
def is_prime(number):
if number < 2:
return False
if number % i == 0:
return False
return True
if is_prime(num):
else:
Output:
Conclusion:
Thus we Used function and write a Python program to analyze the input number is prime or not.
Progrtam Code:
import datetime
current_time = datetime.datetime.now()
"1. Add\n" \
"2. Subtract\n" \
"3. Multiply\n" \
"4. Divide\n")
n=5
for i in range(n):
if select == 1:
add(number_1, number_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")
print("program Ended")
Conclusion:
Thus we Implement a simple Python calculator that takes user input and performs basic
arithmetic operations (addition, subtraction, multiplication, division) using functions
Progrtam Code:
#count_word=4
#if len(word)==count_word:
print(word)
Output:
Conclusion:
Thus we develop a Python program that reads a text file and prints words of specified lengths
(e.g., three, four, five, etc.) found within the file.
Progrtam Code:
# Example of an exception
for i in range(5):
try:
print(result)
except ValueError as e:
except ZeroDivisionError as e:
print(e)
Conclusion:
Thus we write a Python program that takes two numbers as input and performs division.
Implement exception handling to manage division by zero and invalid input errors gracefully.
Debugging in Python is facilitated by pdb module (python debugger) which comes built-in to
the Python standard library. It is actually defined as the class Pdb which internally makes use of
bdb(basic debugger functions) and cmd (support for line-oriented command interpreters)
modules. The major advantage of pdb is it runs purely in the command line, thereby making it
great for debugging code on remote servers when we don’t have the privilege of a GUI-based
debugger.
pdb supports:
Setting breakpoints
To start debugging within the program just insert import pdb, pdb.set_trace() commands. Run
your script normally, and execution will stop where we have introduced a breakpoint. So
basically we are hard coding a breakpoint on a line below where we call set_trace(). With
python 3.7 and later versions, there is a built-in function called breakpoint() which works in the
same manner. Refer following example on how to insert set_trace() function.
Example1: Debugging a Simple Python program of addition of numbers using Python pdb
module
Intentional error: As input() returns string, the program cannot use multiplication on strings.
Thus, it’ll raise ValueError.
import pdb
answer = a * b
return answer
pdb.set_trace()
sum = addition(x, y)
print(sum)
Output :
In the output on the first line after the angle bracket, we have the directory path of our
file, line number where our breakpoint is located, and <module>. It’s basically saying that we
have a breakpoint in exppdb.py on line number 10 at the module level. If you introduce the
breakpoint inside the function, then its name will appear inside <>. The next line is showing
the code line where our execution is stopped. That line is not executed yet. Then we have
the pdb prompt. Now to navigate the code, we can use the following commands :
Command Function
where Display the stack trace and line number of the current line
next Execute the current line and move to the next line ignoring function calls
b = 10
s=0
for i in range(a):
s += a / b
b -= 1
This statement loads your source code and stops execution on the first line of code.
We can navigate in pdb prompt using n (next), u (up), d (down). To debug and navigate all
throughout the Python code, we can navigate using the mentioned commands.
a = 20
b = 10
s=0
for i in range(a):
s += a / b
b -= 1
Output :
answer = a * b
return answer
result = multiply(x, y)
print(result)
Output :
Managing Breakpoints
After adding breakpoints with the help of numbers assigned to them, we can manage the
breakpoints using the enable and disable and remove command. disable tells the debugger
not to stop when that breakpoint is reached, while enable turns on the disabled breakpoints.
Given below is the implementation to manage breakpoints using Example 4.
In this project, you will create a system to manage the products, orders, and customers in an
online store. You will define classes to represent the store, products, orders, and customers.
Here are the steps you can follow to implement this project:
1. Start by designing the layout of the store. Decide on the types of products that you want to
include, and the information that you want to store about each product (e.g. name, price,
description, stock). You may also want to include categories or tags to help organize your
products.
classProduct:
def__init__(self, name, price, description, stock):
self.name = name
self.price = price
self.description = description
self.stock = stock
defupdate_stock(self, quantity):
self.stock += quantity
deftotal_value(self):
returnself.stock * self.price
2. Created a Product class to represent the different products in the store. The Product class should
have attributes to store the product's name, price, description, stock, and any other relevant
information. It should also have methods to update the stock (e.g. when a product is sold or
restocked), and to calculate the total value of the product in the store (i.e. stock x price).
classOrder:
def__init__(self, customer, product, quantity):
self.customer = customer
self.product = product
deftotal_cost(self):
returnself.quantity * self.product.price
3. Created an Order class to represent the orders placed by customers. The Order class should
have attributes to store the customer, the product, and the quantity of the product being ordered. It
should also have a total_cost() method that calculates the total cost of the order.
classCustomer:
def__init__(self, name, email):
self.name = name
self.email = email
self.orders = []
defview_orders(self):
for order inself.orders:
print(order)
4. Created a Customer class to represent the store's customers. The Customer class should have
attributes to store the customer's name, email address, and any other relevant information. It
should also have a place_order() method that allows the customer to place an order for a product,
and a view_orders() method that allows the customer to view all of their past orders.
classStore:
definit(self):
self.products = []
self.orders = []
self.customers = []
defadd_product(self, product):
self.products.append(product)
defdelete_product(self, product):
self.products.remove(product)
defdelete_customer(self, customer):
self.customers.remove(customer)
defadd_order(self, order):
self.orders.append(order)
defdelete_order(self, order):
self.orders.remove(order)
deffind_product(self, name):
for product inself.products:
if product.name == name:
return product
returnNone
deffind_customer(self, name):
for customer inself.customers:
if customer.name == name:
return customer
returnNone
defsales_report(self):
total_sales = 0
for order inself.orders:
total_sales += order.total_cost()
returntotal_sales
defrestock_report(self):
low_stock = []
for product inself.products:
ifproduct.stock<10:
low_stock.append(product)
returnlow_stock
customer1.place_order(product1, 1)
customer2.place_order(product2, 2)
customer1.view_orders()
This code creates a store, adds two products to the store, adds two customers to the store, and then
places two orders. It then prints the total sales for the store and the products with low stock, and
displays the orders placed by customer1.
Actual code:
class Product:
def __init__(self, name, price, description, stock):
self.name = name
self.price = price
self.description = description
self.stock = stock
def total_value(self):
return self.stock * self.price
class Order:
def __init__(self, customer, product, quantity):
self.customer = customer
self.product = product
self.quantity = quantity
def total_cost(self):
return self.quantity * self.product.price
class Customer:
def view_orders(self):
print(f"Orders for {self.name}:")
if not self.orders:
print("No orders placed.")
for order in self.orders:
print(f"Order for {order.product.name} - Quantity: {order.quantity}, Total cost: $
{order.total_cost():.2f}")
class Store:
def __init__(self):
self.products = []
self.orders = []
self.customers = []
def sales_report(self):
total_sales = sum(order.total_cost() for order in self.orders) # Summing up total cost of all
orders
return total_sales
def restock_report(self):
low_stock = []
for product in self.products:
if product.stock < 10:
low_stock.append(product)
return low_stock
store.add_product(product1)
store.add_product(product2)
store.add_customer(customer1)
store.add_customer(customer2)
# Generate reports
print("Total sales: $", store.sales_report()) # Display total sales
print("Low stock:", [product.name for product in store.restock_report()])
Program Code-
#Now, we will use 'Label' method to add widget in the Registration Form and also use place()
method to set their positions.
lbl_0 = Label(base, text="Registration form", width=20,font=("bold",20))
#the place method in tkinter module helps user to set the geometry, that is, the dimensions of a
certain widget by placing them at a certain position
lbl_0.place(x=90,y=60)
#Using Enrty widget to make a text entry box for accepting the input string in text from user.
enter_1 = Entry(base)
enter_1.place(x=240,y=130)
#Using 'Label' widget to create Email label and using place() method to set its position.
lbl_3 = Label(base, text="Email", width=20,font=("bold",10))
lbl_3.place(x=68,y=180)
#Using Enrty widget to make a text entry box for accepting the input string in text from user.
enter_3 = Entry(base)
enter_3.place(x=240,y=180)
#Using 'Label' widget to create Gender label and using place() method to set its position.
lbl_4 = Label(base, text="Gender", width=20,font=("bold",10))
lbl_4.place(x=70,y=230)
#Using Radio button widget to create an option choosing button and using place() method to set
its position.
Radiobutton(base, text="Male", padx= 5, variable= vars, value=1).place(x=235, y=230)
Radiobutton(base, text="Female", padx= 20, variable= vars, value=2).place(x=290,y=230)
#Using 'Label' widget to create Countries label and using place() method, set its position.
lbl_5=Label(base, text ="Country", width=20,font=("bold",11))
lbl_5.place(x=70,y=280)
#the variable 'cv' is introduced to store the String Value, which by default is (empty) ""
cv = StringVar()
drplist = OptionMenu(base, cv, *list_of_cntry)
drplist.config(width=15)
cv.set('Select your Country')
drplist.place(x=240, y=280)
#Using 'Label' widget to create Language label and using place() method, set its position.
lbl_6=Label(base, text="Language", width=20,font=('bold',10))
lbl_6.place(x=75,y=330)
#the new variable 'vars1' is created to store Integer Value, which by default is 0.
vars2=IntVar()
#Using the Checkbutton widget to create a button and using place() method to set its position.
Checkbutton(basetext="German", variable=vars2).place(x=290, y=330)
#Using the Button widget, we get to create a button for submitting all the data that has been
entered in the entry boxes of the form by the user.
Button(base, text='Submit' , width=20, bg="black",fg='white').place(x=180,y=380)
Output:
The output for the aforementioned Simple registration form's code, using Tkinter in Python is
attached below in the form of a screenshot.
Conclusion:
Thus we developed The college admission registration form.
Program Code-
#validation of email id
import re
regex = re.compile(r'([A-Za-z0-9]+[.-_])*[A-Za-z0-9]+@[A-Za-z0-9-]+(\.[A-Z|a-z]{2,})+')
def emailValid(email):
if re.fullmatch(regex, email):
else:
emailValid("[email protected]")
emailValid("[email protected]")
emailValid("[email protected]")
emailValid("[email protected]")
import re
if match:
return True
return False
pattern = re.compile(r"(\+\d{1,3})?\s?\(?\d{1,4}\)?[\s.-]?\d{3}[\s.-]?\d{4}")
"555-123-4567",
"02012345678",
Output:
Conclusion:
Thus we write a Python script that prompts the user to enter their phone number and email ID. It
then employs Regular Expressions to verify if these inputs adhere to standard phone number and
email address formats
Program Code-
import re
deffind_emails(text):
patterns = [r"\S+@\S+"]
email_regex = re.compile(pattern)
emails = email_regex.findall(text)
print(email)
# Example usage
find_emails(text)
Output
Hr@[email protected]
[email protected]
Conclusion:
Thus we create a program that reads a text file containing various data (e.g., names, emails,
phone numbers). Use regular expressions to extract specific types of data, such as email
addresses, phone numbers, dates (e.g., MM/DD/YYYY format).
import numpy as np
print(arr)
#Create a 2-D array containing two arrays with the values 1,2,3 and 4,5,6:
import numpy as np
print(arr)
#Create a 3-D array with two 2-D arrays, both containing two arrays with the values 1,2,3 and
4,5,6:
import numpy as np
print(arr)
#Convert the following 1-D array with 12 elements into a 2-D array.
import numpy as np
newarr = arr.reshape(4, 3)
#Convert the following 1-D array with 12 elements into a 3-D array.
#The outermost dimension will have 2 arrays that contains 3 arrays, each with 2 elements:
import numpy as np
newarr = arr.reshape(2, 3, 2)
print(newarr)
import numpy as np
print(arr[1:5])
import numpy as np
print(arr[4:])
#Slice from the index 3 from the end to index 1 from the end:
print(arr[-3:-1])
Array Indexing
import numpy as np
print(arr[0])
import numpy as np
print(arr[1])
#Get third and fourth elements from the following array and add them.
import numpy as np
print(arr[2] + arr[3])
import numpy as np
import numpy as np
#Access the third element of the second array of the first array:
import numpy as np
arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(arr[0, 1, 2])
Negative Indexing
import numpy as np
Array Mathematics*:
Aim-Develop a Python script to create two arrays of the same shape and perform element-wise
addition, subtraction, multiplication, and division. Calculate the dot product and cross product of
two vectors.
Python Code:
Sample Output:
Add:
5.0
Subtract:
-3.0
Multiply:
4.0
Divide:
0.25
import numpy as np
a = 3 + 1j
b = 7 + 6j
print(np.dot(a, b))
Output:
(15+25j)
# Python Program illustrating
import numpy as np
print(np.dot(a, b))
Output:
[[5 4]
[9 6]]
import numpy as np
print(np.dot(b, a))
n=3
defdotProduct(vect_A, vect_B):
product = 0
return product
# Function to find
# Driver function
if __name__=='__main__':
vect_B = [2, 6, 5]
print(dotProduct(vect_A, vect_B))
Output
Dot product:-4
Cross product:-49 -7 28
Conclusion:
Thus we Develop a Python script to create two arrays of the same shape and perform element-
wise addition, subtraction, multiplication, and division. Calculate the dot product and cross
product of two vectors.
Statistical Operations*:
Aim-Write a Python program to calculate mean, median, standard deviation, variance, and
correlation coefficients of a given array.
import numpy as np
# Original array
array = np.arange(10)
print(array)
r1 = np.mean(array)
r2 = np.std(array)
r3 = np.var(array)
import numpy as np
# Original array
array = np.arange(10)
print(array)
r3 = np.mean((array - np.mean(array)) ** 2)
import numpy as np
# Original array
x = np.arange(5)
print(x)
r11 = np.mean(x)
r12 = np.average(x)
r21 = np.std(x)
r31 = np.var(x)