Andromeda
Note

Input Validation (Python)

Definition

The process of verifying that user-provided data (typically from input()) meets the required format, type, and range constraints before processing it.

Why It Matters

Computer programs are brittle; a single unexpected character (like a letter where a number should be) can cause a total system crash or open a door for a hacker. Input validation is the “immune system” of your code—it ensures that “garbage” stays out so that your program’s internal logic remains safe and predictable. It is the most basic but critical step in building reliable, professional software.

Core Concepts

  • Manual Validation Pattern:
    while True:
        response = input("Enter a number: ")
        try:
            val = int(response)
            if val < 0:
                print("Positive numbers only.")
                continue
            break # Success
        except ValueError:
            print("Numeric digits only.")
  • Infinite Retry vs. Fail-Fast:
    • Infinite Retry: Keeps the program in a loop until valid data is entered (human-centric).
    • Fail-Fast: Uses limit or timeout to exit the input attempt if the user is stubborn or inactive (system-centric).
  • Sanitization vs. Validation: Validation checks the data; sanitization cleans it (e.g., stripping whitespace).

Connected Concepts