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!).
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 > 0Try it yourself
Compare valid input, negative input, and Python’s bool-as-int trap.
| Case | Result |
|---|---|
| can_book(1) | Select a choice above to see what happens. |
| can_book(-1) | Select a choice above to see what happens. |
| can_book(True) without checking isinstance(x, bool) | Select a choice above to see what happens. |
Reveal the explanation
- can_book(1)
Returns True cleanly.
- can_book(-1)
Raises ValueError("INVALID_FREE_SEATS").
- 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.
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
This browser could not save your progress. Changes last until you leave the page.