-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path09_errors.py
More file actions
26 lines (19 loc) · 1.02 KB
/
09_errors.py
File metadata and controls
26 lines (19 loc) · 1.02 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
"""Exercise 09 — Errors & try/except.
Tutorial: https://pythonbeginner.help/learn/using-try-except-else-and-finally-in-python/
TODO:
1. Write `safe_int(text)` that returns `int(text)` if possible,
otherwise returns `None` — without raising an exception.
2. Test it on a few values and store the results in `results`
(a list with three entries: safe_int("42"), safe_int("hi"), safe_int(" 7 ")).
Run: python exercises/09_errors.py
"""
# --- your code below -------------------------------------------------------
def safe_int(text):
... # TODO: try int(text); return None on ValueError
results = [safe_int("42"), safe_int("hi"), safe_int(" 7 ")]
# --- self-check (don't edit) ----------------------------------------------
assert safe_int("42") == 42, "safe_int('42') should return 42"
assert safe_int("hi") is None, "safe_int('hi') should return None"
assert safe_int(" 7 ") == 7, "safe_int(' 7 ') should return 7"
assert results == [42, None, 7], "results list is wrong"
print("✅ Passed!", "results:", results)