Have a go at it. The editor and the docs panel are open, and your code is saved as you type. Running it needs a free account — you’ll come back to exactly what you wrote.
Catching Errors with try / except
Sometimes an error is expected and you want to carry on rather than stop.
try:
value = int(text)
except ValueError:
value = 0Python runs the try block. If the named error happens, it runs the except block instead of crashing. If nothing goes wrong, the except block is skipped.
Name the error you expect. A bare except: swallows everything, including typos in your own code, and turns a five second fix into an afternoon:
try:
value = int(txet) # typo: NameError
except: # silently caught, and now the bug is invisible
value = 0Errors you will meet most: ValueError (right type, wrong content, like int("abc")), TypeError (wrong type entirely), KeyError, IndexError, ZeroDivisionError.
Your task:
Write to_number(text, fallback=0) that converts a string to an integer, returning fallback when the string is not a valid number.
to_number("42") returns 42. to_number("abc") returns 0.
Example Tests
A numeric string converts normally
Input: {"text":"42"}
Expected: 42
A non-numeric string returns the fallback instead of raising
Input: {"text":"abc"}
Expected: 0
An explicit fallback is used instead of 0
Input: {"text":"oops","fallback":-1}
Expected: -1
def to_number(text, fallback=0):
"""
Convert a string to an int, with a fallback for bad input.
Args:
text: the string to convert
fallback: what to return when conversion fails
Returns:
The integer value, or fallback.
"""
# YOUR CODE HERE
passRun your code to see results
⌘↵ runs against the visible tests