How to Validate Input and Raise TypeError in Python

Define a function that checks its argument type and raises a TypeError early with a clear message when given a non-number.

Easy Python 3.6+ Aug 9, 2026 Errors & debugging 14 views 0 copies

Python code

11 lines
Python 3.6+
def validate_number(value):
    if not isinstance(value, (int, float)):
        raise TypeError(f"Expected a number, got {type(value).__name__}")
    return value * 2

if __name__ == "__main__":
    try:
        print(validate_number(5))
        print(validate_number("hello"))
    except TypeError as e:
        print(f"Error: {e}")

Output

stdout
10
Error: Expected a number, got str

How it works

The isinstance check ensures only int or float values are accepted; otherwise a TypeError is raised with a descriptive message that includes the actual type name. By raising the error early, you avoid confusing downstream failures. The try/except block in the main guard demonstrates how to catch and handle the error gracefully.

Common mistakes

  • Using `type(value) == int` which fails for subclasses or boolean values
  • Raising a generic `ValueError` instead of the specific `TypeError`
  • Checking `isinstance(value, (int, float))` but forgetting `bool` is a subclass of `int`
  • Not including the actual type in the error message

Variations

  1. Use Python 3.10+ with `match value:` to validate type patterns
  2. Use a type annotation like `def validate_number(value: int) -> int:` combined with a runtime check

Real-world use cases

  • Validating user input before performing arithmetic in a CLI calculator script.
  • Checking configuration parameters at service startup to fail fast with clear errors.
  • Ensuring numeric fields in API request handlers are the correct type before processing.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Errors & debugging

Related tutorials and quizzes for this topic.