Repository navigation
Expand file tree
/
Copy pathexception_handling_exercises.py
More file actions
73 lines (59 loc) · 2.57 KB
/
Copy pathexception_handling_exercises.py
File metadata and controls
73 lines (59 loc) · 2.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# ==========================================
# Python Learning Lab: 08 Exception Handling
# ==========================================
print("--- Running Exception Handling Exercises ---")
# ==========================================
# Challenge 1: Handling Exceptions (try-except-finally)
# ==========================================
# Write a function that converts a string to an integer and divides 100 by it.
# Handle:
# - ValueError: if the string cannot be converted to an integer. Return -1.
# - ZeroDivisionError: if the input is "0". Return -2.
# Use a finally block to append the message "Checked" to `status_list`.
status_list = []
def safe_divide(val_str):
# TODO: Implement exception handling and finally block
try:
num = int(val_str)
return 100 / num
except ValueError:
return -1
except ZeroDivisionError:
return -2
finally:
status_list.append("Checked")
# --- Verification ---
status_list.clear()
assert safe_divide("5") == 20.0, "Valid division failed"
assert status_list == ["Checked"], "Finally block not executed for success"
status_list.clear()
assert safe_divide("abc") == -1, "Should catch ValueError and return -1"
assert status_list == ["Checked"], "Finally block not executed for ValueError"
status_list.clear()
assert safe_divide("0") == -2, "Should catch ZeroDivisionError and return -2"
assert status_list == ["Checked"], "Finally block not executed for ZeroDivisionError"
print("✓ Challenge 1 passed!")
# ==========================================
# Challenge 2: Custom Exceptions
# ==========================================
# 1. Define a custom exception class `NegativeNumberError` inheriting from `Exception`.
# 2. Complete the function `calculate_square_root` to raise `NegativeNumberError` if the input is negative.
# TODO: Define NegativeNumberError
class NegativeNumberError(Exception):
pass
def calculate_square_root(num):
# For now, let's just return math.sqrt(num) if it's positive.
# TODO: Raise NegativeNumberError if num < 0
if num < 0:
raise NegativeNumberError("Number cannot be negative!")
return num ** 0.5
# --- Verification ---
assert calculate_square_root(9) == 3.0, "Square root calculation failed"
try:
calculate_square_root(-4)
assert False, "Should raise NegativeNumberError"
except Exception as e:
# If the custom exception is implemented, check if it's correct
assert e.__class__.__name__ == "NegativeNumberError", f"Expected NegativeNumberError, got {e.__class__.__name__}"
print("✓ Challenge 2 passed!")
print("\n🎉 All tests passed successfully!")