Python · Exercise 1 of 7Next
Intermediate
Parse a number without crashing
Write a function safe_int(text, default=0) that returns int(text), or default when the text is not a whole number.
It must catch only ValueError, not every error. Then print safe_int("42") and safe_int("x") on two lines. The output should be 42 and then 0.
What Check tests
safe_int("42")returns 42safe_int("x")returns the default 0- A custom default is used
- Spaces around digits are fine
- A decimal text is not a whole number
- Other errors are not hidden
- The program prints 42 then 0
Stuck? One hint at a time
The solution unlocks after your first Check. Try first: that is where the learning happens.
main.py
Sign in to run your code.
Output
Press Run to see what your program prints.