Easy: Warm-Ups · Problem 14 of 82

Safe parse_int

EasyErrors and FilesPython

Write parse_int(text, default=None) that returns int(text) when that works, and default when it does not.

  • The input may be text with spaces (" 7 "), text that is not a number ("abc", "3.5", ""), or not text at all (None).
  • A valid "0" must return 0, not the default.

Understand the problem

Find the errors that int() can raise.

What does int("3.5") raise?

  1. TypeError
  2. ValueError
  3. Nothing, it returns 3

int only accepts text that looks like a whole number, so "3.5" raises ValueError. (To get 3 from "3.5" you would write int(float("3.5")).)

What does int(None) raise?

  1. ValueError
  2. TypeError
  3. Nothing, it returns 0

None is not a string or a number, so int(None) raises TypeError: the type of the argument is wrong. A different exception from the one for bad text, so you must catch both.

A friend writes return int(text) or default. What does parse_int("0", 99) return?

  1. 0
  2. 99

int("0") is 0, which is falsy, so 0 or 99 is 99. A valid zero is replaced by the default. Never use or to pick a default when the real value can be falsy.

Write the solution

Catch the errors you expect and nothing else.

def parse_int(text, default=None):
    # Write your code here.
    pass
Hint 1: a question to ask yourself

Which exceptions can int(text) raise for the inputs in the task?

Hint 2: the shape of the answer

try: return int(text) and except (ValueError, TypeError): return default. Catching a tuple of exception types handles both.

Reflect

Solution

def parse_int(text, default=None):
    try:
        return int(text)
    except (ValueError, TypeError):
        return default

What this tests: try / except, catching several exception types, and not misusing or.

Catch specific exceptions. except Exception or a bare except: would also hide real bugs (a typo like NameError). A bare except: even catches KeyboardInterrupt, which makes the program impossible to stop with Ctrl+C.

try / except / else / finally: else runs when there was no exception, finally always runs (to release resources). Keep the try block small, only the line that can fail.

EAFP: Python prefers "easier to ask forgiveness than permission": try the operation and handle the error, rather than checking in advance (text.isdigit() would wrongly reject "-5" and " 7 ").

What an interviewer might ask next: Make the function also accept "1_000" or reject it. What does int("1_000") do? (It returns 1000: underscores are allowed in numeric text.)