0% found this document useful (0 votes)
14 views6 pages

Lab 13

Uploaded by

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

Lab 13

Uploaded by

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

Programming Fundamentals (SWE-102) SSUET/QR/114

LAB # 13

EXCEPTION HANDLING

OBJECTIVE
Constructing a fault tolerant program by implementing exception handling techniques.

EXERCISE:

A. Point out the errors, if any, and paste the output also in the following Python programs.

1. Code:

instagram = [{'Photos': 6, 'disLikes': 22, 'Comments': 3},


{'disLikes': 13, 'Comments': 1, 'Shares': 6}, {'Photos': 6,
'disLikes': 33, 'Comments': 9, 'Shares': 4}, {'Comments': 5,
'Shares': 1}, {'Photos': 5, 'Comments': 4, 'Shares': 2},
{'Photos': 3, 'disLikes': 19, 'Comments': 3}]
total_dislikes = 0
for post in instagram:
total_dislikes = total_dislikes + post['disLikes']

Correct Code: Output:

instagram = [{'Photos': 6, 'disLikes': 22, 'Comments': 3},


{'disLikes': 13, 'Comments': 1, 'Shares': 6}, {'Photos': 6,
'disLikes': 33, 'Comments': 9, 'Shares': 4}, {'Comments': 5,
'Shares': 1}, {'Photos': 5, 'Comments': 4, 'Shares': 2},
{'Photos': 3, 'disLikes': 19, 'Comments': 3}]
total_dislikes = 0
for post in instagram:
if 'disLikes' in post:
total_dislikes += post['disLikes']
print("Total Dislikes:", total_dislikes)

2. Code:

2023F-BSE-088
Programming Fundamentals (SWE-102) SSUET/QR/114

def Interest(cost, month, rate):


if rate > 100:
raise ValueError(rate)
interest1 = (cost * month * rate) / 100
print('The Interest is', interest1)
return interest1
print('Case 1')
Interest(650, 2, 6)
print('Case 2')
Interest(880, 2, 900)

Correct Code: Output:

def Interest(cost, month, rate):


if rate > 100:
raise ValueError(f"Invalid interest rate: {rate}")
interest = (cost * month * rate) / 100
print('The Interest is', interest)
return interest
print('Case 1')
Interest(650, 2, 6)
print('Case 2')
try:
Interest(880, 2, 900)
except ValueError as e:
print(f"Error: {e}")

3. Code:

my_list = [3,7, 9, 4, 6]
print(my_list[6])
Correct Code: Output:

my_list = [3, 7, 9, 4, 6]
try:
print(my_list[6])
except IndexError as e:
print(f"Error: {e}")
last_element = my_list[-1]
print("Last Element:", last_element)

2023F-BSE-088
Programming Fundamentals (SWE-102) SSUET/QR/114

B. What will be the output of the following programs:

1. Code: Output:

a = 'Hello World!'
try:
a + 10
except BaseException as error:
print('Exception occurred: {}'.format(error))
lst = [5, 10, 20]

2. Code: Output:

lIst = [5, 10, 20]


try:
print(lIst[5])
except IndexError as error:
print('Exception is: {}'.format(type(error).__name__))

3. Code:

import sys
List_random = ['a', 0, 2]
for enter in List_random:
try:
print("The entry is", enter)
r = 1 / int(enter)
break
except:
print("Oops!", sys.exc_info()[0], "occurred.")
print("Next entry.")
print()
print("The reciprocal of", enter, "is", r)

Output

2023F-BSE-088
Programming Fundamentals (SWE-102) SSUET/QR/114

C. Write Python programs for the following:

1. Write a program to make a basic calculator for kids in super market so that they may
verify their calculation using Exceptional Handling. This program must have all four
arithmetic operations.

Code:

def add(x, y):


return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
raise ValueError("Cannot divide by zero.")
return x / y
try:
num1 = float(input("Enter the first number: "))
operation = input("Enter the operation (+, -, *, /): ")
num2 = float(input("Enter the second number: "))
if operation == '+':
result = add(num1, num2)
elif operation == '-':
result = subtract(num1, num2)
elif operation == '*':
result = multiply(num1, num2)
elif operation == '/':
result = divide(num1, num2)
else:
raise ValueError("Invalid operation.")
print(f"The result of {num1} {operation} {num2} is: {result}")
except ValueError as ve:
print(f"Error: {ve}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
Output

2023F-BSE-088
Programming Fundamentals (SWE-102) SSUET/QR/114

2. Write a program to store 5 types of coffee with a number (e.g. Espresso=1, Cappuccino=2,
Macchiato=3 etc.), Now ask the user “which coffee you would like to have, please enter
your desire number”. Use try block to print the coffee name, except block to display if
any invalid number or character has been entered by the user and final block to greet
the customer at last.
Code:

def coffee_menu():
print("Coffee Menu:")
print("1. Espresso")
print("2. Cappuccino")
print("3. Macchiato")
print("4. Latte")
print("5. Americano")
def greet_customer():
print("Thank you for choosing our coffee shop! Enjoy your coffee!")
try:
coffee_menu()
coffee_number = int(input("Enter the number of the coffee you would like to have: "))
coffee_names = {
1: "Espresso",
2: "Cappuccino",
3: "Macchiato",
4: "Latte",
5: "Americano"
}
selected_coffee = coffee_names[coffee_number]
print(f"You selected: {selected_coffee}")
except ValueError:
print("Invalid input. Please enter a number.")
except KeyError:
print("Invalid coffee number. Please select a valid number from the menu.")
finally:
greet_customer()
Output

2023F-BSE-088
Programming Fundamentals (SWE-102) SSUET/QR/114

2023F-BSE-088

You might also like