Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Python Programming Lab Manual

The document is a Python programming lab manual for second-year Cyber Security students, detailing various exercises to be completed. It includes tasks such as calculating customer bills, generating electricity bills based on slab rates, and implementing data structures like lists, sets, and dictionaries. The exercises also cover exception handling, file operations, and class design in Python.

Uploaded by

P.K. Gupta
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)
3 views

Python Programming Lab Manual

The document is a Python programming lab manual for second-year Cyber Security students, detailing various exercises to be completed. It includes tasks such as calculating customer bills, generating electricity bills based on slab rates, and implementing data structures like lists, sets, and dictionaries. The exercises also cover exception handling, file operations, and class design in Python.

Uploaded by

P.K. Gupta
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/ 52

22CS102002- PYTHON PROGRAMMING LAB MANUAL

For Second Year III Semester Cyber Security


LIST OF EXERCISES:

Exp.No Name of the Experiment

1) Design a python script to the perform the various computations for the amount payable by
the customer for Challenger Computers Store. A customer buying two numbers of SSD
device, one SSD device cost is Rs. 3575/-. The stores offer 15% of the total cost. The
customer has to pay 9% CGST, and 9% SGST. Prepare the Net Amount to be payable by the
customer.
2) Design a python script to compute and generate the electricity bill as per the following slab
rates. Collect the meter reading inputs, such as current unit and previous unit.
Consumption Units Rate (in Rupees/Unit)
0-200 3.0
201-250 4.5
251-300 5.2
301-400 6.5
Above 400 7.0
3) Design a python script to display the sum of numbers divisible by 4. The code must allow the
user to accept a number and add it to the sum if it is divisible by 4. It should repeatedly
accepting numbers as long as the user wants to provide an input using an appropriate iterative
statement and should display the final sum.
4) Food Corner home delivers vegetarian and non-vegetarian combos to its customer based on
order. A vegetarian combo costs Rs.120 per plate and a non-vegetarian combo costs Rs.150
per plate. Their non-veg combo is really famous that they get more orders for their non-
vegetarian combo than the vegetarian combo. Apart from the cost per plate of food,
customers are also charged for home delivery based on the distance in kms from the restaurant
to the delivery point. The delivery charges are as mentioned below:
Distance in kms Delivery charge in Rs per km
For first 3 kms 0
For Next 3 kms 3
For the remaining 6
Given the type of food, quantity (no. of plates) and the distance in kms from the restaurant
to the delivery point, write a python program to calculate the final bill amount to be paid by
a customer. The below information must be used to check the validity of the data provided
by the customer.
• Type of food must be ‘V’ for vegetarian and ‘N’ for non-vegetarian.
• Distance in kms must be greater than 0.
• Quantity ordered should be minimum 1.
• If any of the input is invalid, bill amount should be considered as -1.
5) a) A list has the AP City Names [Tirupati, Kurnool, Kadapa]. Design a python script and
perform the operations like, add 3 more AP City names Chittoor, Nellore, Guntur,
insert Hyderabad in 3rd position, delete any two city names, update all city names as in
Uppercase. Displays the list data, whenever an operation completes.

b) Design a python script for given an integer tuple, for each element in the tuple, check
whether there exists a smaller element on the next immediate position of the tuple. If it
exists print the smaller element. If there is no smaller element on the immediate next to
the element then print -1.
Example: Input: 4 2 1 5 3 Output: 2 1 -1 3 -1
6) a) Sets n1 has the data {1, 3, 5, 7, 9}, n2 has the data {9, 5, 6, 8},
wd1=set(["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]),
wd2=set(["Mon", "Tue", "Wed"]).
Design a python script to perform intersection, difference, and symmetric difference
operations on the sets n1 and n2, and to perform superset, and subset operations on the
sets wd1, and wd2.

b) The dictionary city_pin has the data {'Tirupati': 517101, 'Hyderabad': 500002, 'Chittoor':
517001,'Nellore': 524001}. Design a python script using lambda function to sort the
dictionary on city name and produce the output and sort the dictionary on pincode and
produce the output.

c) The string has the data, Wel_str = "Welcome to AI ML DS". Design a python script to
search the pattern “AI” using regular expression search and display the three location
numbers of the pattern. First shows the pattern starts location, second shows the pattern
end location, and the last shows pattern span locations.
7) a) Design a python script for the mathematical puzzle, Towers of Hanoi. The puzzle has
three rods and n disks. To move the entire stack to another rod, obeying the three rules
(i) Only one disk can be moved at a time, (ii) Each move consists of taking the upper
disk from one of the stacks and placing it on top of another stack i.e., a disk can only be
moved if it is the uppermost disk on a stack, (iii) No disk may be placed on top of a
smaller disk.

b) Design a python script to display the numbers that do not appear in the Fibonacci series
of n numbers where n is given by the user. (If n is 8 then up to 8 Fibonacci numbers has
to be printed Ex: 1 1 2 3 5 8 13 21 and in this series missing numbers should be traced
and printed, Ex: missing numbers are: 4 6 7 9 10 11 12 14 15 16 17 18 19.
8) a) Design a function Learner_Age_Days with two formal parameters name, age and it
computes Learner’s age in days, then displays learners name and age in days.
(i) Design a driver code to call the function using positional arguments, keyword
arguments
(ii) Apply the necessary changes in Learner_Age_Days function, and design a driver
code to call the function using default arguments.

b) Design a python script using lambda and filter functions to construct an odd numbers
list from numbers 1 to 10, and construct a negative numbers list from range of numbers
-7 to 7 and to find the biggest number from a numbers list.
9) a) Design a python script to create a new file Collect_Literals_Phython.txt, collect the data
from the keyboard about the contents of collection literals list, tuple, sets, dictionaries
details, then write all the data into that file, and then close that file. Afterwards Open the
Collect_Literals_Phython.txt file in read mode, read the entire contents of the file
Collect_Literals_Phython.txt, then display all the contents of that file in monitor.

b) The file feat_python1.txt has the contents of features of the Python programming
language. Design a python script to open that file feat_python1.txt in read mode, open
the new file in feat_python2.txt in write mode, then read entire contents of the file
feat_python1.txt, then copy all the contents of that file into the new file feat_python2.txt
10) a) Construct a Python script to implement the below requirements. Create a base class
Basic_Info with data members name, rollno, gender and two member functions getdata()
and display(). Derive a class Physical_Fit from Basic_Info which has data members
height and weight and member functions getdata() and display(). Display all the
information using object of derived class.

b) Design a Python script to implement the below specifications, compute, and produce
required output. Define a class REPORT with the following specification
Private members
Admno : 4-digit admission number
Name : 20 characters
Marks : A list of 5 floating point values Average: average marks
obtained
GETAVG() a function to compute the average obtained in five subjects.
Public members
READINFO() function to accept values for Adno, Name, Marks. Invoke the function
GETAVG ().
DISPLAYINFO() function to display all data members of report on the screen. You
should give function definitions. Write driver code to demonstrate all the functions.
11) a) The below scenarios will create Logical Error/Exception, and it will forcibly stop the
execution in middle of the program. Design a Python Script the to handle these
operations exceptions effectively, and avoid to stop the script execution in the middle.
i. The variable num has the data 100, the value of num dividing by the value 0.
ii. To importing a library file matheqn, this library file not available in Python.
iii. A num_List has the values[10,20,30].To print the fifth value of num_List[5]
iv. A dictionary has the data, Dict_Univ = {'1':"MBU", '2':"Tirupathi", '3':"CSE"}. to
print the fifth key value Dict_Univ[5]

b) Design a python script to collect the 10 students Python course mark. Check that entered
mark is negative, then throw a user defined exception called Negative, otherwise store
into the mark in the List Python_mark[].
1. Design a python script to perform the various computations for the amount payable by the
customer for Challenger Computers Store. A customer buying two numbers of SSD device,
one SSD device cost is Rs. 3575/-. The stores offer 15% of the total cost. The customer has
to pay 9% CGST, and 9% SGST. Prepare the Net Amount to be payable by the customer.

Step-by-step procedure to achieve this:


• Total Cost Before Discount: 3575 * 2 = 7150
• Discount Amount: 7150 * 0.15 = 1072.50
• Discounted Price: 7150 - 1072.50 = 6077.50
• CGST: 6077.50 * 0.09 = 546.98
• SGST: 6077.50 * 0.09 = 546.98
• Total GST Amount: 546.98 + 546.98 = 1093.96
• Net Amount Payable: 6077.50 + 1093.96 = 7171.46

Coding:
cost_per_ssd = 3575.0 # Define the cost of one SSD device
number_of_ssds = 2 # Number of SSD devices being purchased
# Calculate the total cost before discount
total_cost_before_discount = cost_per_ssd * number_of_ssds
discount_rate = 15 / 100 # Store offers a discount of 15%
discount_amount = total_cost_before_discount * discount_rate
discounted_price = total_cost_before_discount - discount_amount
cgst_rate = 9 / 100 # GST rates
sgst_rate = 9 / 100
cgst_amount = discounted_price * cgst_rate # Calculate CGST and SGST
sgst_amount = discounted_price * sgst_rate
total_gst = cgst_amount + sgst_amount # Calculate the total GST amount
# Calculate the net amount payable by the customer
net_amount_payable = discounted_price + total_gst
# Print the results
print(f"Total cost before discount: Rs. {total_cost_before_discount:.2f}")
print(f"Discount amount: Rs. {discount_amount:.2f}")
print(f"Discounted price: Rs. {discounted_price:.2f}")
print(f"CGST (9%): Rs. {cgst_amount:.2f}")
print(f"SGST (9%): Rs. {sgst_amount:.2f}")
print(f"Total GST amount: Rs. {total_gst:.2f}")
print(f"Net amount payable: Rs. {net_amount_payable:.2f}")

Output:
Total cost before discount: Rs. 7150.00
Discount amount: Rs. 1072.50
Discounted price: Rs. 6077.50
CGST (9%): Rs. 546.98
SGST (9%): Rs. 546.98
Total GST amount: Rs. 1093.95
Net amount payable: Rs. 7171.45

Result:
2. Design a python script to compute and generate the electricity bill as per the following slab
rates. Collect the meter reading inputs, such as current unit and previous unit.
Consumption Units Rate(in Rupees/Unit)
0-200 3.0
201-250 4.5
251-300 5.2
301-400 6.5
Above 400 7.0

Step-by-step procedure to achieve this:


1. Initialize bill_amount to 0.
2. Determine the slab applicable to the given units consumed:
• Up to 200 units: Charge at ₹3.0 per unit.
• 201 to 250 units: Charge the first 200 units at ₹3.0, and the remaining units (200
to 250) at ₹4.5 per unit.
• 251 to 300 units: Charge the first 200 units at ₹3.0, the next 50 units (201 to 250)
at ₹4.5, and the remaining units (250 to 300) at ₹5.2 per unit.
• 301 to 400 units: Charge the first 200 units at ₹3.0, the next 50 units (201 to 250)
at ₹4.5, the following 50 units (251 to 300) at ₹5.2, and the remaining units (300
to 400) at ₹6.5 per unit.
• Above 400 units: Charge the first 200 units at ₹3.0, the next 50 units (201 to 250)
at ₹4.5, the following 50 units (251 to 300) at ₹5.2, the next 100 units (301 to 400)
at ₹6.5, and any units beyond 400 at ₹7.0 per unit.
3. Return the calculated bill_amount.

Coding:
# Function to calculate the electricity bill based on consumption units
def calculate_electricity_bill(units):
bill_amount = 0
# Calculate bill based on slab rates
if units <= 200:
bill_amount = units * 3.0
elif units <= 250:
bill_amount = (200 * 3.0) + ((units - 200) * 4.5)
elif units <= 300:
bill_amount = (200 * 3.0) + (50 * 4.5) + ((units - 250) * 5.2)
elif units <= 400:
bill_amount = (200 * 3.0) + (50 * 4.5) + (50 * 5.2) + ((units - 300) * 6.5)
else:
bill_amount = (200 * 3.0) + (50 * 4.5) + (50 * 5.2) + (100 * 6.5) + ((units - 400) * 7.0)
return bill_amount

# Main program
def main():
try:
# Collect meter readings from the user
previous_units = float(input("Enter the previous meter reading (in units): "))
current_units = float(input("Enter the current meter reading (in units): "))

# Validate inputs
if previous_units < 0 or current_units < 0:
print("Meter readings must be non-negative.")
return

if current_units < previous_units:


print("Current meter reading cannot be less than previous meter reading.")
return

# Calculate units consumed


units_consumed = current_units - previous_units

if units_consumed <= 0:
print("Invalid reading. No units consumed.")
return

# Calculate the electricity bill


bill_amount = calculate_electricity_bill(units_consumed)

# Display the result


print(f"Total units consumed: {units_consumed}")
print(f"Electricity bill amount: Rs. {bill_amount:.2f}")

except ValueError:
print("Invalid input. Please enter numerical values for meter readings.")
# Run the main program
if __name__ == "__main__":
main()
Output:
Enter the previous meter reading (in units): 200
Enter the current meter reading (in units): 350
Total units consumed: 150.0
Electricity bill amount: Rs. 450.00
Result:
3. Design a python script to display the sum of numbers divisible by 4.The code must allow
the user to accept a number and add it to the sum if it is divisible by 4. It should repeatedly
accepting numbers as long as the user wants to provide an input using an appropriate
iterative statement and should display the final sum.

Step-by-step procedure to achieve this:


1. Initialize total_sum to 0.
2. Start an infinite loop to continuously prompt the user for input.
3. Check if the user wants to exit by typing 'exit'.
4. Convert the input to an integer if it's not 'exit'.
5. Validate if the number is divisible by 4.
6. Accumulate the sum of numbers divisible by 4.
7. Handle invalid inputs gracefully.
8. Display the final accumulated sum after exiting the loop.
Coding:
# Initialize the sum
total_sum = 0

while True:
# Ask the user for input
user_input = input("Enter a number (or type 'exit' to finish): ")

# Check if the user wants to exit the loop


if user_input.lower() == 'exit':
break

try:
# Convert the input to an integer
number = int(user_input)

# Check if the number is divisible by 4


if number % 4 == 0:
total_sum += number
else:
print(f"{number} is not divisible by 4 and will not be added to the sum.")

except ValueError:
print("Invalid input. Please enter a numerical value.")

# Display the final sum


print(f"The final sum of numbers divisible by 4 is: {total_sum}")
Output:
Enter a number (or type 'exit' to finish): 44
Enter a number (or type 'exit' to finish): 40
Enter a number (or type 'exit' to finish): 52
Enter a number (or type 'exit' to finish): 48
Enter a number (or type 'exit' to finish): exit
The final sum of numbers divisible by 4 is: 184
Result:
4. Food Corner home delivers vegetarian and non-vegetarian combos to its customer based
on order. A vegetarian combo costs Rs.120 per plate and a non-vegetarian combo costs
Rs.150 per plate. Their non-veg combo is really famous that they get more orders for
their non-vegetarian combo than the vegetarian combo. A part from the cost per plate of
food, customers are also charged for home delivery based on the distance in kms from
the restaurant to the delivery point. The delivery charges are as mentioned below:
Distance in kms Delivery charge in Rs per km
For first 3 kms 0
For Next 3 kms 3
For the remaining 6

Given the type of food, quantity (no. of plates) and the distance in kms from the
restaurant to the delivery point, write a python program to calculate the final bill
amount to be paid by a customer. The below information must be used to check the
validity of the data provided by the customer.
• Type of food must be‘V’for vegetarian and ‘N’for non-vegetarian.
• Distance in kms must be greaterthan0.
• Quantity ordered should be minimum1.
• If any of the input is invalid, bill amount should be considered as-1.

Step-by-step procedure to achieve this:


• Define constants for cost per plate.
• Create a function to calculate delivery charges based on distance.
• Collect and validate user inputs (food type, quantity, distance).
• Calculate food cost and delivery charge if inputs are valid.
• Display the final bill or an error message based on the validity of inputs.
Coding:
# Constants
VEGETARIAN_COST_PER_PLATE = 120
NON_VEGETARIAN_COST_PER_PLATE = 150
# Delivery charge rates
def calculate_delivery_charge(distance):
if distance <= 3:
return 0
elif distance <= 6:
return (distance - 3) * 3
else:
return 3 * 3 + (distance - 6) * 6

# Collect user inputs


food_type = input("Enter the type of food (V for Vegetarian, N for Non-Vegetarian):
").strip().upper()
quantity = int(input("Enter the quantity (number of plates): ").strip())
distance = float(input("Enter the distance in kms from the restaurant to the delivery point:
").strip())

# Initialize bill amount


bill_amount = -1

# Validate inputs
if food_type in ['V', 'N'] and quantity >= 1 and distance > 0:
# Calculate food cost
if food_type == 'V':
food_cost = VEGETARIAN_COST_PER_PLATE * quantity
else:
food_cost = NON_VEGETARIAN_COST_PER_PLATE * quantity

# Calculate delivery charge


delivery_charge = calculate_delivery_charge(distance)

# Calculate total bill


bill_amount = food_cost + delivery_charge

# Display the result


if bill_amount == -1:
print("Invalid input. Bill amount cannot be calculated.")
else:
print(f"The final bill amount to be paid is: Rs. {bill_amount:.2f}")

Output:
Enter the type of food (V for Vegetarian, N for Non-Vegetarian): v
Enter the quantity (number of plates): 5
Enter the distance in kms from the restaurant to the delivery point: 10
The final bill amount to be paid is: Rs. 633.00
Result:
5. A) A list has the AP City Names [Tirupati, Kurnool, Kadapa]. Design a python script
and perform the operations like, add 3 more AP City names Chittoor, Nellore, Guntur,
insert Hyderabad in 3rd position, delete any two city names, update all city names as in
Uppercase. Displays the list data, whenever an operation completes.

Step-by-step procedure to achieve this:


• Initial List: Start with the list of cities: ['Tirupati', 'Kurnool', 'Kadapa'].
• Add Cities: Use the extend() method to add Chittoor, Nellore, and Guntur to the
list.
• Insert City: Use the insert() method to place Hyderabad at the third position
(index 2).
• Delete Cities: Use the remove() method to delete Kadapa and Nellore. You can
modify which cities to remove based on your needs.
• Update to Uppercase: Use a list comprehension to convert all city names to
uppercase.

Coding:
# Initial list of AP city names
cities = ['Tirupati', 'Kurnool', 'Kadapa']

# Function to display the current state of the list


def display_list(cities):
print("Current list of cities:", cities)

# Display initial list


display_list(cities)

# Add 3 more city names


cities.extend(['Chittoor', 'Nellore', 'Guntur'])
print("\nAfter adding Chittoor, Nellore, Guntur:")
display_list(cities)
# Insert Hyderabad in 3rd position (index 2)
cities.insert(2, 'Hyderabad')
print("\nAfter inserting Hyderabad at the 3rd position:")
display_list(cities)

# Delete any two city names (let's remove 'Kadapa' and 'Nellore')
cities.remove('Kadapa')
cities.remove('Nellore')
print("\nAfter deleting Kadapa and Nellore:")
display_list(cities)

# Update all city names to uppercase


cities = [city.upper() for city in cities]
print("\nAfter updating all city names to uppercase:")
display_list(cities)

Output:
Current list of cities: ['Tirupati', 'Kurnool', 'Kadapa']

After adding Chittoor, Nellore, Guntur:


Current list of cities: ['Tirupati', 'Kurnool', 'Kadapa', 'Chittoor', 'Nellore', 'Guntur']

After inserting Hyderabad at the 3rd position:


Current list of cities: ['Tirupati', 'Kurnool', 'Hyderabad', 'Kadapa', 'Chittoor', 'Nellore',
'Guntur']

After deleting Kadapa and Nellore:


Current list of cities: ['Tirupati', 'Kurnool', 'Hyderabad', 'Chittoor', 'Guntur']

After updating all city names to uppercase:


Current list of cities: ['TIRUPATI', 'KURNOOL', 'HYDERABAD', 'CHITTOOR',
'GUNTUR']

Result:
B) Design a python script for given an integer tuple, for each element in the tuple, check
whether there exists a smaller element on the next immediate position of the tuple. If it
exists print the smaller element. If there is no smaller element on the immediate next to the
element then print - Example: Input: 4 2 1 5 3 Output: 2 1 -1 3 -1

Step-by-step procedure to achieve this:


• Input Collection: The user specifies how many integers they will input. The script
collects these integers, ensuring they are valid.
• Tuple Creation: The integers are stored in a tuple.
• Processing: The script compares each element in the tuple with the next one to check
if it is smaller.
• Output: It prints the smaller element if it exists; otherwise, it prints -1.
• Execution: The main() function ties everything together and is run only when the
script is executed directly.
Coding:
def get_user_input():
# Get the number of elements
num_elements = int(input("Enter the number of elements in the tuple: "))

# Initialize an empty list to store the elements


elements = []

# Collect the elements from the user


for _ in range(num_elements):
while True:
try:
# Take integer input from the user
elem = int(input("Enter an integer: "))
elements.append(elem)
break
except ValueError:
print("Invalid input. Please enter an integer.")
# Convert the list to a tuple
tpl = tuple(elements)
return tpl

def check_smaller_elements(tpl):
# Iterate over the tuple except for the last element
for i in range(len(tpl) - 1):
current = tpl[i]
next_elem = tpl[i + 1]

if next_elem < current:


print(next_elem)
else:
print(-1)

def main():
# Get the user input and create the tuple
user_tuple = get_user_input()

# Print the tuple


print("Your tuple:", user_tuple)

# Check for smaller elements and print results


print("Checking for smaller elements on the next immediate position:")
check_smaller_elements(user_tuple)

if __name__ == "__main__":
main()
Output:
Enter the number of elements in the tuple: 5
Enter an integer: 22
Enter an integer: 11
Enter an integer: 10
Enter an integer: 45
Enter an integer: 23
Your tuple: (22, 11, 10, 45, 23)
Checking for smaller elements on the next immediate position:
11
10
-1
23

Result:
6. A) Sets n1 has the data {1, 3, 5, 7, 9}, n2 has the data {9, 5, 6, 8},
wd1=set(["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]),
wd2=set(["Mon", "Tue", "Wed"]).
Design a python script to perform intersection, difference, and symmetric difference
operations on the sets n1 and n2, and to perform superset, and subset operations on the
sets wd1, and wd2.

It focuses on:
1. Set intersections
2. Set differences
3. Set symmetric differences
4. Superset and subset checks

Code:
def main():
# Define the sets
n1 = {1, 3, 5, 7, 9}
n2 = {9, 5, 6, 8}
wd1 = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}
wd2 = {"Mon", "Tue", "Wed"}

# Intersection of n1 and n2
intersection = n1.intersection(n2)
print("Intersection of n1 and n2:", intersection)

# Difference of n1 and n2 (n1 - n2)


difference_n1_n2 = n1.difference(n2)
print("Difference of n1 and n2 (n1 - n2):", difference_n1_n2)

# Difference of n2 and n1 (n2 - n1)


difference_n2_n1 = n2.difference(n1)
print("Difference of n2 and n1 (n2 - n1):", difference_n2_n1)
# Symmetric difference between n1 and n2
symmetric_difference = n1.symmetric_difference(n2)
print("Symmetric difference between n1 and n2:", symmetric_difference)

# Check if wd1 is a superset of wd2


is_superset = wd1.issuperset(wd2)
print("wd1 is a superset of wd2:", is_superset)

# Check if wd2 is a subset of wd1


is_subset = wd2.issubset(wd1)
print("wd2 is a subset of wd1:", is_subset)

if __name__ == "__main__":
main()

Output:

Intersection of n1 and n2: {9, 5}


Difference of n1 and n2 (n1 - n2): {1, 3, 7}
Difference of n2 and n1 (n2 - n1): {8, 6}
Symmetric difference between n1 and n2: {1, 3, 6, 7, 8}
wd1 is a superset of wd2: True
wd2 is a subset of wd1: True

Result:
B) The dictionary city_pin has the data {'Tirupati': 517101, 'Hyderabad': 500002, 'Chittoor':
517001,'Nellore': 524001}. Design a python script using lambda function to sort the
dictionary on city name and produce the output and sort the dictionary on pincode and
produce the output.
Sorting by City Name:
• city_pin.items() returns a view object of the dictionary's items (key-value pairs).
• sorted() sorts these items based on the key.
• key=lambda item: item[0] specifies that sorting should be based on the city name
(which is the key in each (key, value) pair).
• dict() converts the sorted list of tuples back into a dictionary.

Sorting by Pin Code:


• sorted() sorts the items based on the value.
• key=lambda item: item[1] specifies that sorting should be based on the pin code
(which is the value in each (key, value) pair).
• dict() converts the sorted list of tuples back into a dictionary.

Code:
# Define the dictionary
city_pin = {'Tirupati': 517101, 'Hyderabad': 500002, 'Chittoor': 517001, 'Nellore': 524001}

# Sort the dictionary by city name


sorted_by_city_name = dict(sorted(city_pin.items(), key=lambda item: item[0]))
print("Sorted by city name:")
print(sorted_by_city_name)

# Sort the dictionary by pin code


sorted_by_pin_code = dict(sorted(city_pin.items(), key=lambda item: item[1]))
print("\nSorted by pin code:")
print(sorted_by_pin_code)
Output:
Sorted by city name:
{'Chittoor': 517001, 'Hyderabad': 500002, 'Nellore': 524001, 'Tirupati': 517101}

Sorted by pin code:


{'Hyderabad': 500002, 'Chittoor': 517001, 'Tirupati': 517101, 'Nellore': 524001}

Result:
c) The string has the data, Wel_str = "Welcome to AI ML DS". Design a python script to search
the pattern “AI” using regular expression search and display the three location numbers of the
pattern. First shows the pattern starts location, second shows the pattern end location, and the
last shows pattern span locations.

Procedure:
1. Import the re module: This allows you to work with regular expressions in Python.
2. Define the string and pattern:
• Wel_str is the string where you are searching for the pattern.
• pattern is the substring you're searching for.
3. Use re.search to find the pattern:
• re.search(pattern, Wel_str) searches for the first occurrence of the pattern in
Wel_str.
4. Check if a match was found:
• If match is not None, you can get the start, end, and span of the match:
• match.start() gives the starting index of the matched pattern.
• match.end() gives the ending index of the matched pattern.
• match.span() returns a tuple containing both the start and end indices.
5. Print the results:
• If a match is found, the start, end, and span are printed.
• If no match is found, it prints "Pattern not found".

Code:
import re

# Define the string


Wel_str = "Welcome to AI ML DS"

# Define the pattern to search


pattern = "AI"
# Use re.search to find the pattern
match = re.search(pattern, Wel_str)

# Check if the pattern was found


if match:
# Start location
start_location = match.start()
print("Pattern starts at location:", start_location)

# End location
end_location = match.end()
print("Pattern ends at location:", end_location)

# Span locations
span_locations = match.span()
print("Pattern span locations:", span_locations)
else:
print("Pattern not found")

Output:
Pattern starts at location: 11
Pattern ends at location: 13
Pattern span locations: (11, 13)

Result:
7. A) Design a python script for the mathematical puzzle, Towers of Hanoi. The puzzle has
three rods and n disks. To move the entire stack to another rod, obeying the three rules (i)
Only one disk can be moved at a time, (ii) Each move consists of taking the upper disk
from one of the stacks and placing it on top of another stack i.e., a disk can only be moved
if it is the uppermost disk on a stack, (iii) No disk may be placed on top of a smaller disk.
Function: towers_of_hanoi
1. Parameters:
• n: The number of disks to move.
• source: The rod from which disks are initially moved.
• auxiliary: The rod used as an intermediate or helper.
• target: The rod to which disks are ultimately moved.
2. Function Definition:
• towers_of_hanoi(n, source, auxiliary, target): This is a recursive function that solves
the problem for n disks.
• source: The rod from which disks are moved.
• auxiliary: The rod used as a temporary holding place.
• target: The rod to which disks are ultimately moved.
3. Base Case:
• If there is only one disk (n == 1), the function simply prints the move from the source
rod to the target rod.
4. Recursive Steps:
• Move n-1 disks from the source rod to the auxiliary rod using the target rod as an
intermediate.
• Move the nth disk from the source rod to the target rod.
• Move the n-1 disks from the auxiliary rod to the target rod using the source rod as an
intermediate.
5. Main Function:
• Prompts the user to input the number of disks.
• Calls the towers_of_hanoi function with the initial rods labeled 'A', 'B', and 'C'.
Code:
def towers_of_hanoi(n, source, auxiliary, target):
if n == 1:
print(f"Move disk 1 from {source} to {target}")
return

# Move n-1 disks from source to auxiliary, so they are out of the way
towers_of_hanoi(n - 1, source, target, auxiliary)

# Move the nth disk from source to target


print(f"Move disk {n} from {source} to {target}")

# Move the n-1 disks from auxiliary to target


towers_of_hanoi(n - 1, auxiliary, source, target)

def main():
while True:
try:
n = int(input("Enter the number of disks: "))
if n < 1:
print("Please enter a positive integer.")
continue
break
except ValueError:
print("Invalid input. Please enter an integer.")

# Call the function with 'A', 'B', and 'C' as the names of the rods
print(f"Solving Towers of Hanoi for {n} disks:")
towers_of_hanoi(n, 'A', 'B', 'C')

if __name__ == "__main__":
main()
Output:
Enter the number of disks: 3
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C

Result:
B)Design a python script to display the numbers that do not appear in the Fibonacci series of
n numbers where n is given by the user. (If n is 8 then up to 8 Fibonacci numbers has to be
printed Ex: 1 1 2 3 5 8 13 21 and in this series missing numbers should be traced and
printed, Ex: missing numbers are: 4 6 7 9 10 11 12 14 15 16 17 18 19.
Procedure:
1. Function generate_fibonacci(n):
• Purpose: Generates the first n Fibonacci numbers.
• Algorithm:
o Start with a = 0 and b = 1.
o Append a to the list of Fibonacci numbers.
o Update a and b to the next Fibonacci numbers using a = b and b = a + b.
o Repeat until you have n Fibonacci numbers.
2. Function find_missing_numbers(fibonacci_numbers):
• Purpose: Determines which numbers are missing from the generated Fibonacci
sequence up to the maximum Fibonacci number.
• Algorithm:
o Define the range of numbers from 1 to the maximum Fibonacci number.
o Create a set of all numbers in this range and a set of Fibonacci numbers.
o Compute the difference to find the missing numbers.
o Return the sorted list of missing numbers.
3. Function main():
• Prompts the user for the number of Fibonacci numbers to generate.
• Calls the generate_fibonacci function to get the list of Fibonacci numbers.
• Uses find_missing_numbers to determine and print missing numbers.
• Includes input validation to ensure the user enters a positive integer.
Code:
def generate_fibonacci(n):
if n <= 0:
return []
fibonacci_numbers = []
a, b = 0, 1
while len(fibonacci_numbers) < n:
fibonacci_numbers.append(a)
a, b = b, a + b
return fibonacci_numbers
def find_missing_numbers(fibonacci_numbers):
if not fibonacci_numbers:
return []
max_fib = max(fibonacci_numbers)
all_numbers = set(range(1, max_fib + 1))
fibonacci_set = set(fibonacci_numbers)
missing_numbers = sorted(all_numbers - fibonacci_set)
return missing_numbers
def main():
while True:
try:
n = int(input("Enter the number of Fibonacci numbers to generate: "))
if n < 1:
print("Please enter a positive integer greater than 0.")
continue
break
except ValueError:
print("Invalid input. Please enter an integer.")

# Generate Fibonacci numbers


fibonacci_numbers = generate_fibonacci(n)
if fibonacci_numbers:
print("Fibonacci numbers:")
print(' '.join(map(str, fibonacci_numbers)))

# Find and print missing numbers


missing_numbers = find_missing_numbers(fibonacci_numbers)
if missing_numbers:
print("Missing numbers:")
print(' '.join(map(str, missing_numbers)))
else:
print("No missing numbers within the range.")
else:
print("No Fibonacci numbers generated.")

if __name__ == "__main__":
main()

Output:
Enter the number of Fibonacci numbers to generate: 8
Fibonacci numbers:
0 1 1 2 3 5 8 13
Missing numbers:
4 6 7 9 10 11 12

Result:
8. A) Design a function Learner_Age_Days with two formal parameters name, age and it
computes Learner’s age in days, then displays learners name and age in days.
(i) Design a driver code to call the function using positional arguments, keyword
arguments
(ii) Apply the necessary changes in Learner_Age_Days function, and design a driver
code to call the function using default arguments.

Function Definition

Function Learner_Age_Days:
1. Parameters:
• name (string): The learner's name.
• age (integer): The learner's age in years.
2. Functionality:
• Computes the learner's age in days.
• Displays the learner's name and age in days.
1. Function with Positional and Keyword Arguments
Function Definition:
• Positional Arguments: The function is called with name and age specified in the
order they are defined.
• Keyword Arguments: The function is called with name and age specified by name,
allowing for more flexible argument order.

Code:
def Learner_Age_Days(name, age):
# Assuming each year has 365 days
age_in_days = age * 365
print(f"Learner's Name: {name}")
print(f"Learner's Age in Days: {age_in_days}")

# Driver code to call the function with positional arguments


Learner_Age_Days('Saivishnu', 25)
# Driver code to call the function with keyword arguments
Learner_Age_Days(name='hari', age=30)

Output:
Learner's Name: Saivishnu
Learner's Age in Days: 9125
Learner's Name: hari
Learner's Age in Days: 10950

2. Function with Default Arguments


Updated Function Definition:
• Default Arguments: The function has default values for name and age. If no
arguments are provided, it uses these defaults.
• One Default Argument: When only one argument is provided, the other uses its
default value.
• All Arguments Provided: When both arguments are provided, the function uses
these values.
Code:
def Learner_Age_Days(name='Unknown', age=0):
# Assuming each year has 365 days
age_in_days = age * 365
print(f"Learner's Name: {name}")
print(f"Learner's Age in Days: {age_in_days}")

# Driver code to call the function with default arguments


Learner_Age_Days()

# Driver code to call the function with one default argument


Learner_Age_Days(name='Charlie')
# Driver code to call the function with all arguments provided
Learner_Age_Days(name='Dana', age=22)
Output:
Learner's Name: Unknown
Learner's Age in Days: 0
Learner's Name: Charlie
Learner's Age in Days: 0
Learner's Name: Dana
Learner's Age in Days: 8030

Result:
8.b) Design a python script using lambda and filter functions to construct an odd numbers list from
numbers 1 to 10, and construct a negative numbers list from range of numbers -7 to 7 and to find the
biggest number from a numbers list.
Procedure:
1. Construct a list of odd numbers from 1 to 10.
2. Construct a list of negative numbers from the range -7 to 7.
3. Find the biggest number from a list of numbers.
1. Odd Numbers from 1 to 10:
• Range: Use range(1, 11) to generate numbers from 1 to 10 (inclusive).
• Filter: Use filter with a lambda function lambda x: x % 2 != 0 to select odd numbers.
• Conversion: Convert the filter object to a list with list().
2. Negative Numbers from -7 to 7:
• Range: Use range(-7, 8) to generate numbers from -7 to 7 (inclusive).
• Filter: Use filter with a lambda function lambda x: x < 0 to select negative numbers.
• Conversion: Convert the filter object to a list with list().
3. Find the Biggest Number:
• Function: Define a function find_max that returns the maximum number from a list
using max().
• Example List: Use a sample list example_numbers and find the biggest number in that
list.
• Check: Ensure the list is not empty before using max().
Code:
# Construct a list of odd numbers from 1 to 10
numbers_1_to_10 = list(range(1, 11))
odd_numbers = list(filter(lambda x: x % 2 != 0, numbers_1_to_10))
print(f"Odd numbers from 1 to 10: {odd_numbers}")

# Construct a list of negative numbers from -7 to 7


numbers_neg7_to_7 = list(range(-7, 8))
negative_numbers = list(filter(lambda x: x < 0, numbers_neg7_to_7))
print(f"Negative numbers from -7 to 7: {negative_numbers}")
# Find the biggest number from a list of numbers
def find_max(numbers):
return max(numbers) if numbers else None

# Example list of numbers


example_numbers = [3, 5, -2, 7, -8, 4, 9]

# Find the biggest number from the example list


biggest_number = find_max(example_numbers)
print(f"The biggest number from the list {example_numbers} is: {biggest_number}")

Output:
Odd numbers from 1 to 10: [1, 3, 5, 7, 9]
Negative numbers from -7 to 7: [-7, -6, -5, -4, -3, -2, -1]
The biggest number from the list [3, 5, -2, 7, -8, 4, 9] is: 9

Result:
9. A) Design a python script to create a new file Collect_Literals_Phython.txt, collect the
data from the keyboard about the contents of collection literals list, tuple, sets, dictionaries
details, then write all the data into that file, and then close that file. Afterwards Open the
Collect_Literals_Phython.txt file in read mode, read the entire contents of the file
Collect_Literals_Phython.txt, then display all the contents of that file in monitor.
Procedure:
• Collect Data: Collect information from the user about list, tuple, set, and
dictionary collection literals.
• Write Data: Write this collected information into a file named
Collect_Literals_Phython.txt.
• Read Data: Open the file in read mode, read its contents, and display the contents
on the monitor.
1. Function collect_data():
• Prompts the user to input details about lists, tuples, sets, and dictionaries.
• Returns the collected data as a tuple of strings.
2. Function write_to_file(filename, data):
• Opens the file specified by filename in write mode ('w').
• Writes the collected data into the file, including labels for each section (list, tuple,
set, dictionary).
3. Function read_from_file(filename):
• Opens the file specified by filename in read mode ('r').
• Reads the entire contents of the file and returns it as a string.
4. Function main():
• Calls collect_data() to get user input.
• Defines the filename where data will be saved.
• Calls write_to_file() to write the data to the file.
• Calls read_from_file() to read the data from the file.
• Prints the contents of the file to the monitor.
Code:
def collect_data():
print("Please provide details about the following collection literals:")

# Collect details about list


list_data = input("Enter the list details (e.g., [1, 2, 3, 4]): ")

# Collect details about tuple


tuple_data = input("Enter the tuple details (e.g., (1, 2, 3, 4)): ")

# Collect details about set


set_data = input("Enter the set details (e.g., {1, 2, 3, 4}): ")

# Collect details about dictionary


dict_data = input("Enter the dictionary details (e.g., {'a': 1, 'b': 2}): ")

return list_data, tuple_data, set_data, dict_data

def write_to_file(filename, data):


"""
Write collected data to a file.

:param filename: The name of the file to write data to.


:param data: The data to write to the file.
"""
with open(filename, 'w') as file:
file.write("List Details:\n")
file.write(data[0] + "\n\n")
file.write("Tuple Details:\n")
file.write(data[1] + "\n\n")
file.write("Set Details:\n")
file.write(data[2] + "\n\n")
file.write("Dictionary Details:\n")
file.write(data[3] + "\n")
def read_from_file(filename):
"""
Read data from a file and return its contents.

:param filename: The name of the file to read data from.


:return: The contents of the file as a string.
"""
with open(filename, 'r') as file:
contents = file.read()
return contents

def main():
# Collect data from the user
data = collect_data()

# Define the filename


filename = 'Collect_Literals_Phython.txt'

# Write the data to the file


write_to_file(filename, data)

# Read the contents from the file


file_contents = read_from_file(filename)

# Display the contents


print("\nContents of the file:")
print(file_contents)

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

Result:
9.b) The file feat_python1.txt has the contents of features of the Python programming
language. Design a python script to open that file feat_python1.txt in read mode, open the
new file in feat_python2.txt in write mode, then read entire contents of the file
feat_python1.txt, then copy all the contents of that file into the new file feat_python2.txt

Step-by-step implementation:
• File Names: We define the names of the source and destination files.
• Reading the Source File:
• We use a with statement to open feat_python1.txt in read mode ('r'). This ensures the file is
properly closed after its suite finishes.
• We read the entire contents of the file into the variable content using src.read().
• Writing to the Destination File:
• We open feat_python2.txt in write mode ('w'). If feat_python2.txt doesn’t exist, it will be
created. If it does exist, it will be overwritten.
• We write the contents of content to the destination file using dest.write(content).
• Completion Message: We print a confirmation message to indicate that the operation is
complete.
Code:
# Define file names
source_file = 'feat_python1.txt'
destination_file = 'feat_python2.txt'

# Open the source file in read mode


with open(source_file, 'r') as src:
# Read the entire contents of the source file
content = src.read()

# Open the destination file in write mode


with open(destination_file, 'w') as dest:
# Write the contents to the destination file
dest.write(content)
print(f"Contents of {source_file} have been copied to {destination_file}.")
Output:

Result:
10.a) Construct a Python script to implement the below requirements. Create a base class
Basic_Info with data members name, rollno, gender and two member functions getdata() and
display(). Derive a class Physical_Fit from Basic_Info which has data members height and
weight and member functions getdata() and display(). Display all the information using object
of derived class.
Step-by-step implementation:
1. Define the base class Basic_Info with data members name, rollno, and gender. It will
also have member functions getdata() to input data and display() to print the data.
• __init__: Initializes the basic attributes.
• getdata(): Prompts the user to input values for name, rollno, and gender.
• display(): Prints the values of name, rollno, and gender.
2. Define the derived class Physical_Fit which inherits from Basic_Info. This class will
add data members height and weight, and override the getdata() and display() methods
to handle the additional attributes.
• Inherits from Basic_Info.
• __init__: Calls the base class constructor using super().__init__() and
initializes additional attributes height and weight.
• getdata(): Calls the base class getdata() to input basic information, then inputs
height and weight.
• display(): Calls the base class display() to print basic information, then prints
height and weight.
3. Main Code Block:Physical_Fit and use it to input and display the information.
• Creates an instance of Physical_Fit.
• Calls getdata() to input all required information.
• Calls display() to show the gathered information.

Code:
# Base class
class Basic_Info:
def __init__(self):
self.name = ""
self.rollno = ""
self.gender = ""

def getdata(self):
self.name = input("Enter name: ")
self.rollno = input("Enter roll number: ")
self.gender = input("Enter gender: ")

def display(self):
print("Name:", self.name)
print("Roll Number:", self.rollno)
print("Gender:", self.gender)

# Derived class
class Physical_Fit(Basic_Info):
def __init__(self):
super().__init__()
self.height = 0
self.weight = 0

def getdata(self):
super().getdata() # Call the base class getdata method
self.height = float(input("Enter height (in cm): "))
self.weight = float(input("Enter weight (in kg): "))

def display(self):
super().display() # Call the base class display method
print("Height:", self.height, "cm")
print("Weight:", self.weight, "kg")

# Main code
if __name__ == "__main__":
student = Physical_Fit()
student.getdata()
print("\nStudent Information:")
student.display()
Output:
Enter name: Saiteja
Enter roll number: 12
Enter gender: male
Enter height (in cm): 175
Enter weight (in kg): 65

Student Information:
Name: Saiteja
Roll Number: 12
Gender: male
Height: 175.0 cm
Weight: 65.0 kg
Result:
10.b) Design a Python script to implement the below specifications, compute, and produce required
output. Define a class REPORT with the following specification
Private members
Admno : 4-digit admission number
Name : 20 characters
Marks : A list of 5 floating point values Average: average marks obtained
GETAVG() a function to compute the average obtained in five subjects.
Public members
READINFO() function to accept values for Adno, Name, Marks. Invoke the function GETAVG ().
DISPLAYINFO() function to display all data members of report on the screen. You should give
function definitions. Write driver code to demonstrate all the functions.
Step-by-step implementation:
1. Class REPORT:
• Private Members:
a) ‘__admno’: Stores the admission number.
b) ‘__name’: Stores the name.
c) ‘__marks’: List of marks for 5 subjects.
d) ‘__average’: Stores the computed average of marks.
• Private Method __getavg():
a) Computes and returns the average of the marks.
• Public Method READINFO():
a) Accepts input values for Admno, Name, and Marks.
b) Validates and handles input to ensure correct format and range.
c) Calls __getavg() to compute the average.
• Public Method DISPLAYINFO():
a) Displays the admission number, name, marks, and computed average.
2. Driver Code:
• Creates an instance of the REPORT class.
• Calls READINFO() to input data.
• Calls DISPLAYINFO() to print the report details.
Code:
class REPORT:
def __init__(self):
# Initialize private members
self.__admno = ""
self.__name = ""
self.__marks = [0.0] * 5
self.__average = 0.0

def __getavg(self):
# Compute the average of marks
if len(self.__marks) == 0:
return 0.0
self.__average = sum(self.__marks) / len(self.__marks)
return self.__average

def READINFO(self):
# Accept values for Admno, Name, and Marks
self.__admno = input("Enter 4-digit admission number: ")
while len(self.__admno) != 4 or not self.__admno.isdigit():
print("Invalid admission number. It must be 4 digits.")
self.__admno = input("Enter 4-digit admission number: ")

self.__name = input("Enter name (up to 20 characters): ")


while len(self.__name) > 20:
print("Name is too long. It must be 20 characters or less.")
self.__name = input("Enter name (up to 20 characters): ")

# Accept marks for 5 subjects


for i in range(5):
while True:
try:
mark = float(input(f"Enter mark for subject {i+1}: "))
if 0 <= mark <= 100:
self.__marks[i] = mark
break
else:
print("Mark must be between 0 and 100.")
except ValueError:
print("Invalid input. Please enter a numeric value.")

# Invoke GETAVG to compute average


self.__getavg()

def DISPLAYINFO(self):
# Display all data members
print("\nReport Details:")
print(f"Admission Number: {self.__admno}")
print(f"Name: {self.__name}")
print(f"Marks: {', '.join(map(str, self.__marks))}")
print(f"Average Marks: {self.__average:.2f}")

# Driver code to demonstrate the functionality


if __name__ == "__main__":
report = REPORT()
report.READINFO()
report.DISPLAYINFO()

Output:
Enter 4-digit admission number: 1001
Enter name (up to 20 characters): Sai
Enter mark for subject 1: 85
Enter mark for subject 2: 85
Enter mark for subject 3: 89
Enter mark for subject 4: 50
Enter mark for subject 5: 35

Report Details:
Admission Number: 1001
Name: Sai
Marks: 85.0, 85.0, 89.0, 50.0, 35.0
Average Marks: 68.80

Result:
11.a) The below scenarios will create Logical Error/Exception, and it will forcibly stop the
execution in middle of the program. Design a Python Script the to handle these operations
exceptions effectively, and avoid to stop the script execution in the middle.
i. The variable num has the data 100, the value of num dividing by the value 0.
ii. To importing a library file matheqn, this library file not available in Python.
iii. A num_List has the values[10,20,30].To print the fifth value of num_List[5]
iv. A dictionary has the data, Dict_Univ = {'1':"MBU", '2':"Tirupathi", '3':"CSE"}. to print the
fifth key value Dict_Univ[5]
Implementation:
1. Exception Handling: Each scenario uses a try block to execute the code that may
raise an exception, followed by an except block to handle the specific type of
exception that might occur.
2. Script Execution: The script will handle each type of error gracefully and continue to
execute without stopping abruptly, allowing for smoother error management and user
experience.
Explanation: This code attempts to access a key '5' in the dictionary Dict_Univ, which does
not exist. The except block catches the KeyError and prints an error message.

Code:
def handle_exceptions():
# Scenario 1: Division by zero
try:
num = 100
result = num / 0
except ZeroDivisionError:
print("Error: Cannot divide by zero.")

# Scenario 2: Importing a non-existent library


try:
import matheqn # This library does not exist
except ImportError:
print("Error: The library 'matheqn' is not available.")

# Scenario 3: Accessing an out-of-range index in a list


try:
num_List = [10, 20, 30]
print("Fifth value in num_List:", num_List[5])
except IndexError:
print("Error: Index out of range. List has only 3 elements.")

# Scenario 4: Accessing a non-existent key in a dictionary


try:
Dict_Univ = {'1': "MBU", '2': "Tirupathi", '3': "CSE"}
print("Value for key '5':", Dict_Univ['5'])
except KeyError:
print("Error: Key '5' not found in the dictionary.")

# Driver code to demonstrate exception handling


if __name__ == "__main__":
handle_exceptions()

Output:
ERROR!
Error: Cannot divide by zero.
ERROR!
Error: The library 'matheqn' is not available.
Error: Index out of range. List has only 3 elements.
Error: Key '5' not found in the dictionary.
Result:
11.b) Design a python script to collect the 10 students Python course mark. Check that
entered mark is negative, then throw a user defined exception called Negative, otherwise
store into the mark in the List Python_mark[].
Implementation:
1. Define a user-defined exception called Negative.
2. Create a function to collect marks from the user.
3. Check if the entered mark is negative and raise the Negative exception if so.
4. Store valid marks in a list Python_mark[].

Code:
# Define user-defined exception
class Negative(Exception):
def __init__(self, message="Negative mark is not allowed."):
self.message = message
super().__init__(self.message)

def collect_marks():
Python_mark = []
for i in range(10):
while True:
try:
mark = float(input(f"Enter mark for student {i+1}: "))
if mark < 0:
# Raise user-defined exception for negative marks
raise Negative()
Python_mark.append(mark)
break # Exit the loop once a valid mark is entered
except ValueError:
# Handle non-numeric input
print("Invalid input. Please enter a numeric value.")
except Negative as e:
# Handle negative mark error
print(e)

return Python_mark

# Driver code
if __name__ == "__main__":
marks = collect_marks()
print("\nCollected Marks:")
print(marks)

Output:
Enter mark for student 1: 98
Enter mark for student 2: -65
Negative mark is not allowed.
Enter mark for student 2: 35
Enter mark for student 3: 69
Enter mark for student 4: 0
Enter mark for student 5: 58
Enter mark for student 6: 75
Enter mark for student 7: 632
Enter mark for student 8: 1
Enter mark for student 9: 23
Enter mark for student 10: 78

Collected Marks:
[98.0, 35.0, 69.0, 0.0, 58.0, 75.0, 63.0, 1.0, 23.0, 78.0]

Result:

You might also like