Curriculum

Curriculum

Reject Invalid Inputs Explicitly in Python

Scenario

Test can_book in Python with 1, -1, and True (remember: in Python, bool is a subclass of int!).

Selected choicePick a choice below
Result—
Python
def can_book(free_seats: int) -> bool:
    if isinstance(free_seats, bool) or not isinstance(free_seats, int) or free_seats < 0:
        raise ValueError("INVALID_FREE_SEATS")
    return free_seats > 0

Try it yourself

Compare valid input, negative input, and Python’s bool-as-int trap.

Reveal the explanation
  1. can_book(1)

    Returns True cleanly.

  2. can_book(-1)

    Raises ValueError("INVALID_FREE_SEATS").

  3. can_book(True) without checking isinstance(x, bool)

    Python trap! isinstance(True, int) is True—checking bool first rejects True explicitly.

Checking isinstance(x, bool) alongside isinstance(x, int) prevents True from sneaking in as integer 1 in Python.

Review first
Download shared test cases

Your turn

Add a ValueError("INVALID_SCORE") guard to did_pass_quiz(score) in Python for score < 0, score > 100, or non-integers.

Common mistake Returning False for -5 instead of raising the documented ValueError.

Check your work

Raises ValueError("INVALID_SCORE") on -5, 105, and "60".

Quick check

Why does the Python guard check "isinstance(free_seats, bool)" separately from "not isinstance(free_seats, int)"?
Show the answer and reasoning

Correct answer Because in Python, bool is a subclass of int so True passes isinstance(True, int)

Checking bool explicitly prevents True/False from being accepted as seat counts 1/0.