Command Palette

Search for a command to run...

Hectal
Phase 7: Errors, Files and Data Formats
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

  1. safe_int("42") returns 42
  2. safe_int("x") returns the default 0
  3. A custom default is used
  4. Spaces around digits are fine
  5. A decimal text is not a whole number
  6. Other errors are not hidden
  7. 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.