01 / 21

Input
Validation

Learn to verify user input before your program uses it: check types, enforce ranges, and handle unexpected data with confidence.

Python

What is Input Validation?

Input validation is the process of checking data provided by a user (or any external source) to make sure it meets the expectations of your program before you try to use it.

Type
Is the data actually a number, string, or list?
Range
Does the value fall within acceptable limits?
Format
Does the input match a required pattern or structure?

Why Does Validation Matter?

User Input Program Logic Crash / Bug / Wrong Result ✕ Without Validation User Input Validate Safe Logic ✓ ✓ With Validation Re-prompt User

Without validation, bad input flows directly into your logic: a user types "abc" where a number is expected and your program crashes with a ValueError.

The Golden Rule of Input

Crashes
Unhandled exceptions terminate your program unexpectedly.
Wrong results
Silently using bad data produces incorrect output.
Security holes
Unvalidated input can lead to injection attacks.

Core Pattern: try / except

try: age = int(input("Enter your age: ")) except ValueError: print("That's not a valid number.")

This is the foundation of type validation in Python. Every time you convert input() to int(), float(), or another type, wrap it in try/except.

The Validation Loop

while True: try: age = int(input("Age (0-120): ")) if 0 <= age <= 120: break print("Age must be 0-120.") except ValueError: print("Enter a whole number.")

Type vs Range Validation

Type Validation Range Validation
Question Can this be converted? Is the value acceptable?
Tool try / except if / elif / else
Catches "abc" → int age = \(-5\) or \(999\)
Error Type ValueError, TypeError Logical / domain error
Order Check first Check second

How to Apply Validation

1
Identify what you need. Determine the expected type (int, float, str) and any constraints (range, length, allowed values).
2
Wrap in a while True loop. This ensures the user is re-prompted until valid input is given.
3
Try the conversion. Use try/except to catch type errors (ValueError for int/float conversions).
4
Check the range. After successful conversion, use if-statements to enforce bounds, then break.
5
Give clear feedback. Tell the user what went wrong and what is expected.

Example 1: Integer in Range

# Ask for a test score between 0 and 100 while True: try: score = int(input("Score (0-100): ")) if 0 <= score <= 100: break print("Must be 0-100.") except ValueError: print("Enter a whole number.") print(f"Your score: {score}")

Example 2: Float with a Lower Bound

# Get a positive temperature in Celsius while True: try: temp = float(input("Temp in C (above -273.15): ")) if temp > -273.15: break print("Below absolute zero!") except ValueError: print("Enter a number.")

Example 3: Constrained String

# Accept only y or n while True: choice = input("Continue? (y/n): ").strip().lower() if choice in ("y", "n"): break print("Please enter y or n.")

Checking Types with isinstance()

def double(x): if not isinstance(x, (int, float)): raise TypeError("x must be a number") return x * 2

When writing functions (not just interactive scripts), use isinstance() to validate argument types. This is especially useful when your function could be called by other code, not just by input().

isinstance(x, int)
Returns True if x is an integer.
isinstance(x, (int, float))
Returns True if x is int or float.

Watch for Edge Cases

Empty input
User presses Enter with no text. int("") raises ValueError.
Whitespace
" 42 " is valid via int(), but " " alone is not. Use .strip() first.
Boundary values
If range is \( 1 \leq n \leq 10 \), test 0, 1, 10, and 11 explicitly.
Negative zero
float("-0") is valid Python and equals 0.0. Rarely a problem, but be aware.

Reusable Validation Function

def get_int(prompt, lo, hi): """Ask until user gives int in [lo, hi].""" while True: try: val = int(input(prompt)) if lo <= val <= hi: return val print(f"Must be {lo}-{hi}.") except ValueError: print("Enter a whole number.") # Usage: age = get_int("Age: ", 0, 120) score = get_int("Score: ", 0, 100)

Common Mistakes

✕ No try/except
Calling int(input(...)) without a try block: one bad keystroke crashes the program.
✕ Range without type
Checking if \( x > 0 \) before converting from string: causes a TypeError or compares strings.
✕ Bare except
Using except: with no error type silently catches all errors, hiding real bugs.
✕ Forgetting the loop
Validating once without a while loop: if the input fails, the program continues with no value.

Validation Summary

Scenario Technique Key Code
String → integer try / except ValueError int(input(...))
String → float try / except ValueError float(input(...))
Value in range if with comparison if lo \(\leq\) x \(\leq\) hi
Value in set if with in if x in ("y","n")
Argument type isinstance + raise isinstance(x, int)
Re-prompting while True + break while True: ... break

Question 1 of 5

What does input() always return in Python?

Question 2 of 5

What exception does int("hello") raise?

Question 3 of 5

If the user enters "7.5", what happens?

Question 4 of 5

Why should you validate type before range?

Question 5 of 5

The user enters "RED". What is printed?