-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path06_errors.py
More file actions
39 lines (31 loc) · 1.06 KB
/
06_errors.py
File metadata and controls
39 lines (31 loc) · 1.06 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
"""
Examples of basic error handling with try / except / else / finally.
This script:
- asks the user for a number
- tries to divide 100 by that number
- handles invalid input and division by zero gracefully
"""
def safe_divide(divisor_str: str) -> str:
"""Try to divide 100 by the given string input.
Returns a message describing the result or the error.
"""
try:
divisor = float(divisor_str)
result = 100 / divisor
except ValueError:
return "Please enter a valid number. For example: 5 or 2.5."
except ZeroDivisionError:
return "You cannot divide by zero. Try a nonzero number."
else:
return f"100 divided by {divisor} is {result}."
finally:
# This block always runs. In a real app, you might use it for cleanup.
# Here we keep it simple to show the structure.
print("safe_divide operation finished.")
def main() -> None:
user_input = input("Enter a number to divide 100 by: ")
message = safe_divide(user_input)
print(message)
if __name__ == "__main__":
main()
3