Catching Errors with try / except

~10 mincode completion

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.

Examples

A numeric string converts normally

Input
to_number("42")
Output
42

A non-numeric string returns the fallback instead of raising

Input
to_number("abc")
Output
0

An explicit fallback is used instead of 0

Input
to_number("oops", -1)
Output
-1

Hints

Hint 1

Work directly with the arguments text, fallback and return the result rather than printing it.

Hint 2

Watch for this: used bare except.

Requirements

  • text: the string to convert

  • fallback: what to return when conversion fails

  • Return the integer value, or fallback.

Constraints

  • Standard library only, no imports required

  • Time limit: 200 ms, Memory: 64 MB

Where this shows up

~10 min

3 employers weight this skill

2 frontier labs, 1 AI product company. Top match scores 80.

Python
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
    pass
Loading docs…

The AI Mentor needs an account

It reads your code and the failing tests and nudges you toward the fix without handing you the answer. Free accounts get it on every problem you're working on today.