Input
Validation
Learn to verify user input before your program uses it: check types, enforce ranges, and handle unexpected data with confidence.
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.
Why Does Validation Matter?
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
Core Pattern: try / except
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
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
Example 1: Integer in Range
Example 2: Float with a Lower Bound
Example 3: Constrained String
Checking Types with isinstance()
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().
Watch for Edge Cases
Reusable Validation Function
Common Mistakes
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
Code:
while True:
try:
n = int(input("Pick 1-10: "))
if 1 \(\leq\) n \(\leq\) 10:
break
print("Out of range.")
except ValueError:
print("Not a number.")
If the user enters "7.5", what happens?
Question 4 of 5
Why should you validate type before range?
Question 5 of 5
Code:
choice = input("Pick a color (red/blue): ")
if choice == "red" or choice == "blue":
print("Good pick!")
else:
print("Invalid color.")
The user enters "RED". What is printed?