Python Lab File
Python Lab File
CIE-332P
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 proposed
PO1,PO2,
R2 design/procedure/algorithm No Partially Completely PSO1, PSO2
PO3
solves the problem?
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
?
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
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 = ""
Output:
30/01/25
EXPERIMENT - 6
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: ")
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
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: "))
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 %): "))
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:
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:
print("___________________________________")
print("Experiment Submitted By:")
print("Garv Baweja")
print(35214802722)
Output:
06/02/25
EXPERIMENT - 9
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")
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")
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
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()
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()
Output:
13/02/25
EXPERIMENT - 13
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
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
Code:
def have_common_elements(list1, list2):
return bool(set(list1) & set(list2))
# Main
list1 = [1, 2, 3, 4]
list2 = [5, 6, 3, 8]
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
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
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.")
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
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
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
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
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
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)
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)
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: