
Fill in
Else and Finally
A try statement has two more optional parts:
try:
n = int(text) # the risky part
except ValueError:
print("bad number") # runs if it failed
else:
print("got", n) # runs only if it did NOT fail
finally:
print("checked") # ALWAYS runs
elseruns only when thetryblock finished without an exception. It lets you keeptrytiny: only the risky line goes there, and the "happy path" goes inelse.finallyruns no matter what: success, failure, or even areturninside the other blocks. It is the place for clean-up, like closing a file or putting tools back.
The order is always try, then except, then else, then finally.
Assignment
Fill in the four ___ blanks in try_light(fuel_text) with the
keywords try, except, else and finally, so that:
"2.5"logs"lit with 2.5"then"checked", and returnsTrue."soup"logs"bad fuel"then"checked", and returnsFalse.
Fill in the four ___ blanks in try_light(fuel_text) with the
keywords try, except, else and finally, so that:
"2.5"logs"lit with 2.5"then"checked", and returnsTrue."soup"logs"bad fuel"then"checked", and returnsFalse.
main.py Python sleeping
Press Run to try your code, then Check to test it.