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

Python Lab File

Uploaded by

zeus408809
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Python Lab File

Uploaded by

zeus408809
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Programming in Python Lab

CIE-332P




Faculty Name: Mr Ashish Sharma

Name: Garv Baweja

Roll No: 35214802722

Group: 6CSE-AIML-II-C
Rubrics for Lab Assessment:
10 Marks POs and PSOs Covered
Rubrics
0 Marks 1 Marks 2 Marks PO PSO

Is able to identify and


R1 define the objective of the No Partially Completely PO1, PO2 PSO1, PSO2
given problem?

Is proposed
PO1,PO2,
R2 design/procedure/algorithm No Partially Completely PSO1, PSO2
PO3
solves the problem?

Has the understanding of


the tool/programming PO1,PO3,
R3 No Partially Completely PSO1, PSO2
language to implement the PO5
proposed solution?

Are the result(s) verified


PO2,PO4,
R4 using sufficient test data to No Partially Completely PSO2
PO5
support the conclusions?

Individuality of
R5 No Partially Completely PO8, PO12 PSO1, PSO3
submission?
LAB INDEX

R1 R2 R3 R4 R5

Has the
underst
Is
Is able anding Are the
propose
to of the result
d
identify
design
tool/pro verified Total
and grammi using Individ Faculty
S.No Experiment /proced Marks Remarks
define
ure
ng sufficie uality Signature
the languag nt test of (10)
/algorit
objectiv e to data to submiss
hm
e of the implem support ion?
solves
given ent the the
the
problem propose conclusi
problem
? d ons?
?
solution
?

2 Marks 2 Marks 2 Marks 2 Marks 2 Marks


Create a
program that
prompts the
user for their
1 name and age
and prints a
personalised
message.
Create a
program that
prompts the
user for their
2 age and tells
them if they can
vote in their first
election.

Create a
program that
calculates the
3 factorial of a
number entered
by the user
using a loop.
Create a
program that
prompts the
user for a list of
4 numbers and
then sorts them
in the ascending
order.
Create a
program that
prompts the
5 user for a string
and then
print-outs string
reversed.
Create a
program that
defines a
function to
6 calculate area of
a circle based
on radius
entered by the
user.
Create a
program that
checks whether
7 the number
entered by the
user is prime or
not.
Create a
program to print
a symmetric
8 pattern around
the vertical
middle line:
Create a
program that
prompts the
user for the
length and width
9 of a rectangle
and then
calculates and
prints the area.​
(Additional 1)
Create a
program that
prompts the
user for the
price of an item
and the sales
10 tax rate (as a
percentage).
Then, calculate
and print the
final price,
including tax.
(Additional 2)
Create a
program that
asks the user for
two numbers
and then prints
11 out which
number is larger
(or if they are
equal).
(Additional 3)
Create a
program that
prompts the
user for their
age and
favourite
12 number. Then,
add their age to
their favourite
number and
print the result.
(Additional 4)
Classes and
objects: Create
a program that
defines a class
to represent a
13 car, and then
creates an
object of that
class with
specific
attributes.
File input/output:
Create a
program that
reads data from
14 a file and writes
it to another file
in a different
format.
Write a program
to find the
maximum and
15 minimum
elements in a
list.
(Additional 5)
Write a program
to remove
duplicates from
16 a list and display
unique
elements.​
(Additional 6)
Write a program
to generate all
permutations
and
17 combinations of
elements in a
list.
(Additional 7)
Create a
program that
uses regular
expressions to
18 find all instances
of a specific
pattern in a text
file.
Create a
program that
prompts the
user for two
19 numbers and
then divides
them, handling
any exceptions
that may arise
Create a
program that
20 prints the
pyramid
pattern-2
Check if list is
21 empty in python.
(Additional 8)
Write a python
program to
rotate a list to
22 the right by a
given number of
positions.
(Additional 9)
Check if two
lists have
common
23 elements in
python
(Additional 10)
Create a
program that
uses a graphical
user interface
24 (GUI) to allow
the user to
perform simple
calculations
Create a
program that
reads data from
a file and then
creates a
25 visualization of
that data using a
data
visualization
library.
Write a program
to find the
longest
26 increasing
subsequence in
list of numbers
(Additional 11)
Write a program
to find the
27 second-largest
number in a list.
(Additional 12)
Write a program
to merge two list
and sort the
28 resulting list in
ascending order.
(Additional 13)
Write a program
29 to reverse a list.
(Additional 14)
Write a Python
program to
pretty-print a list
of dictionaries
containing
30 employee
details (name,
age,
department).
(Additional 15)
Format and
pretty-print a
table displaying
student names
31 and marks using
string
formatting.
(Additional 16)
Design an
Employee class
with attributes
name, ID, and
salary, and a
32 method to give a
percentage-bas
ed salary
increment.
(Additional 17)
Write a Python
program to
reverse each
word in a given
33 string while
maintaining the
word order.
(Additional 18)
Implement a
function to
check whether a
given string is a
valid password
(at least 8
34 characters,
contains digits,
uppercase,
lowercase, and
a special
character).
(Additional 19)
Write a Python
program that
handles
ZeroDivisionErr
35 or and prompts
the user to enter
a valid
denominator
(Additional 20)
Implement a
function that
opens a file and
handles
36 FileNotFoundErr
or if the file does
not exist.
(Additional 21)
Create a
Product class
with attributes
name, price,
and quantity.
Handle
exceptions
37 when setting
price (must be
positive) and
use pretty
printing to
display multiple
products.
(Additional 22)
Implement a
function that
takes a string as
input, stores
each unique
character as a
key in a
dictionary with
38 its frequency as
the value, and
pretty-prints the
dictionary.
Handle
TypeError if
input is not a
string.
(Additional 23)
Develop a
Student class
with attributes
name and
marks (list).
Implement
39 methods to
calculate the
average marks
and format the
output using
pretty printing.
(Additional 24)
16/01/25
EXPERIMENT - 1

Aim: Create a program that prompts the user for their name and age and
prints a personalised message.

Code:
# User input
name = input("Enter your name: ")
age = int(input("Enter your age: "))
# Personalized message
print("Hello " + name + ", you are " + str(age) + " years old!")

Output:



16/01/25
EXPERIMENT - 2

Aim: Create a program that prompts the user for their age and tells them if
they can vote in their first election.

Code:
print("Welcome to Voter Eligibility Checker")
#User input
name = input("Enter your name: ")
age = int(input("Enter your age: "))
#Check
if (age >= 18):
print("Hello " + name + ", you are " + str(age) + " years old and Eligible to cast a vote")
else:
print("Hello " + name + ", you are " + str(age) + " years old and NOT Eligible to cast a vote")

Output:
23/01/25
EXPERIMENT - 3

Aim: Create a program that calculates the factorial of a number entered by


the user using a loop.

Code:
while(True):
# User input
num = int(input("Enter a number to calculate its factorial: "))
factorial = 1

if num < 0:
print("Factorial is not defined for negative numbers.")
elif num == 0:
print("The factorial of '0' is 1.")
else:
# Calculating factorial using a loop
for i in range(1, num + 1):
factorial *= i
print(f"The factorial of {num} is {factorial}.")

Output:
23/01/25
EXPERIMENT - 4

Aim: Create a program that prompts the user for a list of numbers and then
sorts them in the ascending order.

Code:
# Empty list
numbers = []
# Number of elements
n = int(input("How many numbers do you want to enter? "))
# Taking input using a loop
for i in range(n):
num = int(input(f"Enter number {i + 1}: "))
numbers.append(num)
# Bubble sort algorithm
for i in range(len(numbers) - 1):
for j in range(len(numbers) - i - 1):
if numbers[j] > numbers[j + 1]:
# Swap the elements
numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j]
# Display the sorted list
print("Sorted list:", numbers)

Output:
30/01/25
EXPERIMENT - 5

Aim: Create a program that prompts the user for a string and then
print-outs string reversed.

Code:
user_input = input("Enter a string to be reversed: ")
reversed_string = ""

for char in user_input:


reversed_string = char + reversed_string # Append each character at the front

print("Reversed string: ", reversed_string)


print("___________________________________")
print("Experiment Submitted By:")
print("Garv Baweja")
print(35214802722)

Output:
30/01/25
EXPERIMENT - 6

Aim: Create a program that defines a function to calculate area of a circle


based on radius entered by the user.

Code:
def calculate_circle_area(radius):
pi = 22 / 7 # Approximation for Pi
return pi * radius ** 2

# User input
radius = input("Enter the radius of the circle: ")

if radius.replace('.', '', 1).isdigit():


radius = float(radius)
if radius >= 0:
area = calculate_circle_area(radius)
print(f"The area of the circle with radius {radius} is {area:.2f}")
else:
print("Radius cannot be negative.")
else:
print("Please enter a valid number.")
print("___________________________________")
print("Experiment Submitted By:")
print("Garv Baweja")
print(35214802722)

Output:
30/01/25
EXPERIMENT - 7

Aim: Create a program that checks whether the number entered by the user
is prime or not.

Code:
num = int(input("Enter a number: "))

if num <= 1:
print(f"{num} is not a prime number.")
else:
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break

if is_prime:
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")

print("___________________________________")
print("Experiment Submitted By:")
print("Garv Baweja")
print(35214802722)

Output:
30/01/25
EXPERIMENT - 8

Aim: Create a program to print a symmetric pattern around the vertical


middle line:
1
121
12321
1234321
123454321

Code:
for i in range(1, 6):
print(" " * (5 - i), end="") # Add spaces for centering
for j in range(1, i + 1):
print(j, end="")
for j in range(i - 1, 0, -1):
print(j, end="")
print()

print("___________________________________")
print("Experiment Submitted By:")
print("Garv Baweja")
print(35214802722)

Output:
EXPERIMENT - Additional- 1

Aim: Create a program that prompts the user for the length and width of a
rectangle and then calculates and prints the area.

Code:
def calculate_rectangle_area(length, width):
return length * width

try:
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))

if length <= 0 or width <= 0:


print("Length and width must be positive numbers.")
else:
area = calculate_rectangle_area(length, width)
print(f"The area of the rectangle is {area:.2f}")
except ValueError:
print("Please enter valid numbers.")

print("___________________________________")
print("Experiment Submitted By:")
print("Garv Baweja")
print(35214802722)

Output:


EXPERIMENT - Additional- 2

Aim: Create a program that prompts the user for the price of an item and
the sales tax rate (as a percentage). Then, calculate and print the final
price, including tax.

Code:
def calculate_final_price(price, tax_rate):
return price + (price * tax_rate / 100)

try:
price = float(input("Enter the price of the item: "))
tax_rate = float(input("Enter the sales tax rate (in %): "))

if price < 0 or tax_rate < 0:


print("Price and tax rate must be non-negative numbers.")
else:
final_price = calculate_final_price(price, tax_rate)
print(f"The final price including tax is {final_price:.2f}")
except ValueError:
print("Please enter valid numbers.")

print("___________________________________")
print("Experiment Submitted By:")
print("Garv Baweja")
print(35214802722)

Output:
EXPERIMENT - Additional- 3

Aim: Create a program that asks the user for two numbers and then prints
out which number is larger (or if they are equal).

Code:

num1 = float(input("Enter the first number: "))


num2 = float(input("Enter the second number: "))

if num1 > num2:


print(f"{num1} is larger.")
elif num2 > num1:
print(f"{num2} is larger.")
else:
print("Both numbers are equal.")

print("___________________________________")
print("Experiment Submitted By:")
print("Garv Baweja")
print(35214802722)

Output:
EXPERIMENT - Additional- 4

Aim: Create a program that prompts the user for their age and favourite
number. Then, add their age to their favourite number and print the result.

Code:

age = int(input("Enter your age: "))


favorite_number = int(input("Enter your favourite number: "))

result = age + favorite_number


print(f"The result of adding your age and favourite number is: {result}")

print("___________________________________")
print("Experiment Submitted By:")
print("Garv Baweja")
print(35214802722)

Output:
06/02/25
EXPERIMENT - 9

Aim: Classes and objects: Create a program that defines a class to


represent a car, and then creates an object of that class with specific
attributes.

Code:
class Car:
def __init__(self, brand, model, year, color):
self.brand = brand
self.model = model
self.year = year
self.color = color
def display_details(self):
print(f"Car Details:\nBrand: {self.brand}\nModel: {self.model}\nYear: {self.year}\nColor:
{self.color}")
# Create an object of the Car class with specific attributes
my_car = Car("Porchse", "Model 3", 2023, "Red")
my_car.display_details()
print("___________________________________")
print("Experiment Submitted By:")
print("Garv Baweja")
print(35214802722)

Output:
06/02/25
EXPERIMENT - 10

Aim: File input/output: Create a program that reads data from a file and
writes it to another file in a different format.

Code:
# Writing data to a file
with open("input.txt", "w") as input_file:
input_file.write("Hello, this is a test file.\nWelcome to file I/O in Python.")

# Reading data from input file and writing formatted output to another file
with open("input.txt", "r") as input_file, open("output.txt", "w") as output_file:
for line in input_file:
formatted_line = f"Data: {line.strip()}"
output_file.write(formatted_line + "\n")

print("Data successfully written to output.txt")


print("___________________________________")
print("Experiment Submitted By:")
print("Garv Baweja")
print(35214802722)

Output:
06/02/25
EXPERIMENT - Additional- 5

Aim: Write a program to find the maximum and minimum elements in a list.

Code:
# Writing data to a file
with open("input.txt", "w") as input_file:
input_file.write("Hello, this is a test file.\nWelcome to file I/O in Python.")

# Reading data from input file and writing formatted output to another file
with open("input.txt", "r") as input_file, open("output.txt", "w") as output_file:
for line in input_file:
formatted_line = f"Data: {line.strip()}"
output_file.write(formatted_line + "\n")

print("Data successfully written to output.txt")


print("___________________________________")
print("Experiment Submitted By:")
print("Garv Baweja")
print(35214802722)

Output:
06/02/25
EXPERIMENT - Additional- 6

Aim: Write a program to remove duplicates from a list and display unique
elements.

Code:
# Input the number of elements
n = int(input("Enter the number of elements in the list: "))
numbers = []
for i in range(n):
num = int(input(f"Enter element {i + 1}: "))
numbers.append(num)
# Removing duplicates by converting list to a set and back to a list
unique_numbers = list(set(numbers))
print("Unique elements:", unique_numbers)
print("___________________________________")
print("Experiment Submitted By:")
print("Garv Baweja")
print(35214802722)

Output:
06/02/25
EXPERIMENT - Additional- 7

Aim: Write a program to generate all permutations and combinations of


elements in a list.

Code:
def generate_permutations(current_list, start_index, end_index):
if start_index == end_index:
print(current_list)
else:
for i in range(start_index, end_index + 1):
current_list[start_index], current_list[i] = current_list[i], current_list[start_index]
generate_permutations(current_list, start_index + 1, end_index)
current_list[start_index], current_list[i] = current_list[i], current_list[start_index]
# Input list size
n = int(input("Enter the number of elements in the list: "))
elements = [input(f"Enter element {i + 1}: ") for i in range(n)]
print("Permutations:")
generate_permutations(elements, 0, n - 1)
print("___________________________________")
print("Experiment Submitted By:")
print("Garv Baweja")
print(35214802722)
Output:
13/02/25
EXPERIMENT - 11

Aim: Create a program that uses regular expressions to find all instances
of a specific pattern in a text file.

Code:
import re
file_name = "sample.txt"
with open(file_name, "r") as file:
content = file.read()

print("File Content:\n" + content)


# Getting regex pattern from user
pattern = input("Enter the pattern to search for: ")
# Find all occurrences
matches = re.findall(pattern, content)
print("Pattern found:", matches)
print("___________________________________")
print("Experiment Submitted By:")
print("Garv Baweja")
print(35214802722)

Output:
13/02/25
EXPERIMENT - 12

Aim: Create a program that prompts the user for two numbers and then
divides them, handling any exceptions that may arise (such as division by
zero or invalid input).

Code:
import re
file_name = "sample.txt"
with open(file_name, "r") as file:
content = file.read()

print("File Content:\n" + content)


# Getting regex pattern from user
pattern = input("Enter the pattern to search for: ")
# Find all occurrences
matches = re.findall(pattern, content)
print("Pattern found:", matches)
print("___________________________________")
print("Experiment Submitted By:")
print("Garv Baweja")
print(35214802722)

Output:
13/02/25
EXPERIMENT - 13

Aim: Create a program that prints the pyramid pattern-2

Code:
row = int(input('Enter how many lines? '))
for i in range(1, row + 1):
# for space
for j in range(1, row + 1 - i):
print(' ', end='')
# for increasing pattern
for j in range(1, i + 1):
print(j, end='')
# for decreasing pattern
for j in range(i - 1, 0, -1):
print(j, end='')
# Moving to next line
print("")
print("___________________________________")
print("Experiment Submitted By:")
print("Garv Baweja")
print(35214802722)

Output:
20/02/25
EXPERIMENT - Additional- 8

Aim: Check if list is empty in python.

Code:
import random

def check_empty(l1):
if (len(l1) == 0):
return 0
else:
return 1
# main
status = True
while status == True:
num1 = []
for i in range(0, random.randint(0, 5)):
num1.append(i)
print(num1)
if check_empty(num1) == 0:
status = False
print("Empty list found")
print("___________________________________")
print("\nExperiment Submitted By:")
print("Garv Baweja")
print(35214802722)

Output:
20/02/25
EXPERIMENT - Additional- 9

Aim: Write a python program to rotate a list to the right by a given number
of positions.

Code:
# Function to rotate list to the right
def rotate_list_right(lst, k):
if not lst:
return lst
k = k % len(lst) # Handle rotations greater than list size
return lst[-k:] + lst[:-k]
# Main
lst = [1, 2, 3, 4, 5]
k = int(input("Enter number of positions to rotate: "))
rotated = rotate_list_right(lst, k)
print("Original List:", lst)
print("Rotated List:", rotated)

print("___________________________________")
print("\nExperiment Submitted By:")
print("Garv Baweja")
print(35214802722)

Output:
20/02/25
EXPERIMENT - Additional- 10

Aim: Check if two lists have common elements in python

Code:
def have_common_elements(list1, list2):
return bool(set(list1) & set(list2))
# Main
list1 = [1, 2, 3, 4]
list2 = [5, 6, 3, 8]

print("List 1:", list1)


print("List 2:", list2)
if have_common_elements(list1, list2):
print("The lists have common elements.")
else:
print("The lists do not have any common elements.")
# Your details at the end
print("___________________________________")
print("\nExperiment Submitted By:")
print("Garv Baweja")
print(35214802722)

Output:
27/02/25
EXPERIMENT - 14

Aim: Create a program that uses a graphical user interface (GUI) to allow
the user to perform simple calculations

Code:
import tkinter as tk
def calculate():
try:
result = eval(entry.get())
result_label.config(text="Result: " + str(result))
except Exception as e:
result_label.config(text="Error: Invalid Input")
window = tk.Tk()
window.title("Simple Calculator")
entry = tk.Entry(window, width=30)
entry.pack(pady=10)
calc_button = tk.Button(window, text="Calculate", command=calculate)
calc_button.pack()
result_label = tk.Label(window, text="Result: ")
result_label.pack(pady=10)
window.mainloop()

Output:
27/02/25
EXPERIMENT - 15

Aim: Create a program that reads data from a file and then creates a
visualization of that data using a data visualization library.

Code:
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv("data.csv")
plt.figure(figsize=(8, 5))
plt.bar(data["Category"], data["Value"], color=["red", "yellow", "pink", "brown", "purple"])
plt.xlabel("Category")
plt.ylabel("Value")
plt.title("Fruit Sales Data")
plt.xticks(rotation=30)
plt.show()

Output:
13/03/25
EXPERIMENT - Additional- 11

Aim: Write a program to find the longest increasing subsequence in list of


numbers

Code:
def longest_increasing_subsequence(nums):
if not nums:
return []
n = len(nums)
dp = [1] * n
prev_index = [-1] * n
max_len = 1
last_index = 0
for i in range(1, n):
for j in range(i):
if nums[i] > nums[j] and dp[j] + 1 > dp[i]:
dp[i] = dp[j] + 1
prev_index[i] = j
if dp[i] > max_len:
max_len = dp[i]
last_index = i
lis = []
while last_index != -1:
lis.append(nums[last_index])
last_index = prev_index[last_index]
return lis[::-1] # Reverse to get correct order
nums = [10, 22, 9, 33, 21, 50, 41, 60]
print("Original List:", nums)
print("Longest Increasing Subsequence:", longest_increasing_subsequence(nums))
print("___________________________________")
print("\nExperiment Submitted By:")
print("Garv Baweja")
print(35214802722)

Output:
13/03/25
EXPERIMENT - Additional- 12

Aim: Write a program to find second-largest number in a list.

Code:
def find_second_largest(numbers):
if len(numbers) < 2:
return None # Not enough elements
first = second = float('-inf')
for num in numbers:
if num > first:
second = first
first = num
elif first > num > second:
second = num
return second if second != float('-inf') else None
nums = [12, 45, 1, -10, 34, 45, 7]
print("Original List:", nums)
second_largest = find_second_largest(nums)
if second_largest is not None:
print("Second Largest Number:", second_largest)
else:
print("No second largest number found.")

# Your details at the end


print("___________________________________")
print("\nExperiment Submitted By:")
print("Garv Baweja")
print(35214802722)

Output:
13/03/25
EXPERIMENT - Additional- 13

Aim: Write a program to merge two list and sort the resulting list in
ascending order.

Code:
def merge_and_sort(list1, list2):
merged_list = list1 + list2
merged_list.sort()
return merged_list
list1 = [5, 2, 9, 1]
list2 = [8, 3, 7, 6]
result = merge_and_sort(list1, list2)
print("List 1:", list1)
print("List 2:", list2)
print("Merged and Sorted List:", result)
print("___________________________________")
print("\nExperiment Submitted By:")
print("Garv Baweja")
print(35214802722)

Output:
13/03/25
EXPERIMENT - Additional- 14

Aim: Write a program to reverse a list.

Code:
def reverse_list_with_loop(lst):
reversed_list = []
for i in range(len(lst) - 1, -1, -1):
reversed_list.append(lst[i])
return reversed_list
original_list = [10, 20, 30, 40, 50]
reversed_list = reverse_list_with_loop(original_list)
print("Original List:", original_list)
print("Reversed List:", reversed_list)
print("___________________________________")
print("\nExperiment Submitted By:")
print("Garv Baweja")
print(35214802722)

Output:
13/03/25
EXPERIMENT - Additional- 15

Aim: Write a Python program to pretty-print a list of dictionaries containing


employee details (name, age, department).

Code:
import pprint
def pretty_print_employees(employees):
if not employees:
print("No employee data available.")
return
pprint.pprint(employees, sort_dicts=False)
employees = [
{"Name": "Alice Johnson", "Age": 30, "Department": "HR"},
{"Name": "Bob Smith", "Age": 25, "Department": "IT"},
{"Name": "Charlie Brown", "Age": 35, "Department": "Finance"}
]
pretty_print_employees(employees)
print("___________________________________")
print("\nExperiment Submitted By:")
print("Garv Baweja")
print(35214802722)

Output:
13/03/25
EXPERIMENT - Additional- 16

Aim: Format and pretty-print a table displaying student names and marks
using string formatting.

Code:
def pretty_print_students(students):
# Header
print("{:<20} {:>10}".format("Student Name", "Marks"))
print("-" * 30)
for student in students:
print("{:<20} {:>10}".format(student["name"], student["marks"]))
students = [
{"name": "Ananya Sharma", "marks": 87},
{"name": "Ravi Kumar", "marks": 92},
{"name": "Sneha Gupta", "marks": 78},
{"name": "Arjun Mehta", "marks": 85} ]
pretty_print_students(students)
print("___________________________________")
print("\nExperiment Submitted By:")
print("Garv Baweja")
print(35214802722)

Output:
20/03/25
EXPERIMENT - Additional- 17

Aim: Design an Employee class with attributes name, ID, and salary, and a
method to give a percentage-based salary increment.

Code:
class Employee:
def __init__(self, name, emp_id, salary):
self.name = name
self.emp_id = emp_id
self.salary = salary
def apply_increment(self, percentage):
increment = self.salary * (percentage / 100)
self.salary += increment
print(f"Salary of {self.name} (ID: {self.emp_id}) increased by {percentage}% to
{self.salary:.2f}")
emp1 = Employee("Garima Singh", 101, 50000)
emp2 = Employee("Rohit Verma", 102, 62000)
emp1.apply_increment(10)
emp2.apply_increment(7.5)
print("___________________________________")
print("\nExperiment Submitted By:")
print("Garv Baweja")
print(35214802722)

Output:
20/03/25
EXPERIMENT - Additional- 18

Aim: Write a Python program to reverse each word in a given string while
maintaining the word order.

Code:
def reverse_words_in_string(input_string):
# Split the string into words, reverse each word, and join them back with spaces
words = input_string.split()
reversed_words = [word[::-1] for word in words]
return " ".join(reversed_words)
input_string = "Hello World from Python"
result = reverse_words_in_string(input_string)
print("Original String:", input_string)
print("Reversed Words String:", result)
print("___________________________________")
print("\nExperiment Submitted By:")
print("Garv Baweja")
print(35214802722)

Output:
20/03/25
EXPERIMENT - Additional- 19

Aim: Implement a function to check whether a given string is a valid


password (at least 8 characters, contains digits, uppercase, lowercase, and
a special character).

Code:
import re
def is_valid_password(password):
# Check if the password meets all conditions
if len(password) < 8:
return "Password must be at least 8 characters long."
if not re.search(r"[0-9]", password):
return "Password must contain at least one digit."
if not re.search(r"[A-Z]", password):
return "Password must contain at least one uppercase letter."
if not re.search(r"[a-z]", password):
return "Password must contain at least one lowercase letter."
if not re.search(r"[!@#$%^&*(),.?\":{}|<>]", password):
return "Password must contain at least one special character."
return "Password is valid."
password = input("Enter a password: ")
result = is_valid_password(password)
print(result)
print("___________________________________")
print("\nExperiment Submitted By:")
print("Garv Baweja")
print(35214802722)

Output:
27/03/25
EXPERIMENT - Additional- 20

Aim: Write a Python program that handles ZeroDivisionError and prompts


the user to enter a valid denominator

Code:
def divide_numbers():
try:
numerator = float(input("Enter the numerator: "))
denominator = float(input("Enter the denominator: "))
# Perform division
result = numerator / denominator
print(f"Result: {result}")
except ZeroDivisionError:
print("Error: Denominator cannot be zero. Please enter a valid denominator.")
# Recursive call to prompt for valid input
divide_numbers()
divide_numbers()
print("___________________________________")
print("\nExperiment Submitted By:")
print("Garv Baweja")
print(35214802722)

Output:
27/03/25
EXPERIMENT - Additional- 21

Aim: Implement a function that opens a file and handles FileNotFoundError


if the file does not exist.

Code:
def open_file(filename):
try:
# Try to open the file
with open(filename, 'r') as file:
content = file.read()
print("File content successfully read:")
print(content)
except FileNotFoundError:
print(f"Error: The file '{filename}' does not exist.")
# Prompt the user to enter a new file name
new_filename = input("Please enter a valid file name: ")
open_file(new_filename)

# Example usage
file_name = input("Enter the file name to open: ")
open_file(file_name)

# Your details at the end


print("___________________________________")
print("\nExperiment Submitted By:")
print("Garv Baweja")
print(35214802722)

Output:
03/03/25
EXPERIMENT - Additional- 22

Aim: Create a Product class with attributes name, price, and quantity.
Handle exceptions when setting price (must be positive) and use pretty
printing to display multiple products.

Code:
def open_file(filename):
try:
# Try to open the file
with open(filename, 'r') as file:
content = file.read()
print("File content successfully read:")
print(content)
except FileNotFoundError:
print(f"Error: The file '{filename}' does not exist.")
# Prompt the user to enter a new file name
new_filename = input("Please enter a valid file name: ")
open_file(new_filename)

# Example usage
file_name = input("Enter the file name to open: ")
open_file(file_name)

# Your details at the end


print("___________________________________")
print("\nExperiment Submitted By:")
print("Garv Baweja")
print(35214802722)

Output:
03/03/25
EXPERIMENT - Additional- 23

Aim: Implement a function that takes a string as input, stores each unique
character as a key in a dictionary with its frequency as the value, and
pretty-prints the dictionary. Handle TypeError if input is not a string.

Code:
import pprint
def character_frequency(input_string):
# Handle TypeError if input is not a string
if not isinstance(input_string, str):
raise TypeError("Input must be a string.")
frequency_dict = {}
for char in input_string:
if char in frequency_dict:
frequency_dict[char] += 1
else:
frequency_dict[char] = 1
pprint.pprint(frequency_dict)
try:
user_input = input("Enter a string: ")
character_frequency(user_input)
except TypeError as e:
print(f"Error: {e}")
print("___________________________________")
print("\nExperiment Submitted By:")
print("Garv Baweja")
print(35214802722)
Output:
03/03/25
EXPERIMENT - Additional- 24

Aim: Develop a Student class with attributes name and marks (list).
Implement methods to calculate the average marks and format the output
using pretty printing. Handle ValueError if marks contain invalid data.

Code:
import pprint
class Student:
def __init__(self, name, marks):
self.name = name
self.set_marks(marks) # Initialize marks using the setter method to handle errors
def set_marks(self, marks):
# Validate that all elements in marks are numbers
if not all(isinstance(mark, (int, float)) for mark in marks):
raise ValueError("Marks must be numeric values (int or float).")
self.marks = marks
def calculate_average(self):
# Calculate and return the average marks
return sum(self.marks) / len(self.marks) if self.marks else 0
def get_student_details(self):
# Return student details as a dictionary
return {
"Name": self.name,
"Marks": self.marks,
"Average Marks": self.calculate_average()
}
def pretty_print_students(students):
if not students:
print("No student data available.")
return
pprint.pprint([student.get_student_details() for student in students], sort_dicts=False)
students = []

try:
students.append(Student("Alice", [85, 90, 88, 92]))
students.append(Student("Bob", [78, 81, "95", 87])) # This will raise an exception
except ValueError as e:
print(f"Error: {e}")
try:
students.append(Student("Charlie", [65, 70, 75, 80]))
except ValueError as e:
print(f"Error: {e}")
pretty_print_students(students)
print("___________________________________")
print("\nExperiment Submitted By:")
print("Garv Baweja")
print(35214802722)

Output:

You might also like