COMPUTER PROGRAMMING 1 (PYTHON) • STRINGS & TEXT PROCESSING

Input Validation — I can validate user input (digits, ranges, allowed choices) and handle invalid cases gracefully.

Learn to protect your programs from unexpected input so they never crash on real users.

Historical Context & Motivation

Every program that accepts user input faces a fundamental problem: people make mistakes. They type letters where numbers are expected, enter values that are way out of range, or choose options that don't exist. In the early days of computing, programs simply crashed when they received bad input—there was no safety net. As software became more widespread in the 1960s and 1970s, engineers realized that input validation—the practice of checking user-supplied data before processing it—was essential for building reliable, user-friendly software.

1960s
Batch Processing Errors
Early mainframe programs ran in batch mode. A single typo on a punch card could waste hours of processing time, making programmers painfully aware of the need to check input before executing.
1970s
Interactive Terminals Emerge
Users began interacting with computers through terminals in real time. Programs needed to prompt, check, and re-prompt—giving birth to the validation loop pattern still used today.
1988
The Morris Worm
The first major internet worm exploited programs that did not validate the length of input. This event proved that missing validation is not just an annoyance—it is a security vulnerability.
2000s
Web Forms & SQL Injection
As the web exploded, attackers discovered they could inject malicious commands through unvalidated form fields. Input validation became a cornerstone of web security education.
Today
Validation Everywhere
From mobile apps to APIs, every modern platform validates input at multiple layers. Python's readable syntax makes it an ideal language to learn these essential patterns.

The core question this lesson addresses is straightforward: how do you write Python code that gracefully handles any input a user might provide, instead of crashing or producing wrong results? By the end, you will be able to validate digits, check ranges, restrict choices, and loop until the user gets it right.

Core Principles of Input Validation

Input validation rests on a few key ideas that apply whether you're writing a simple calculator or a complex web application. Understanding these principles first will make every validation technique you learn feel logical and connected.

1

Never Trust User Input

Always assume the user will provide something unexpected. Design your code to check before you process, never after.
2

Fail Gracefully

When input is invalid, show a clear, helpful error message and give the user another chance rather than letting the program crash.
3

Validate Type First, Then Value

Check that the data is the right type (e.g., digits only) before checking if it falls in a valid range or matches allowed choices.
4

Use Loops for Re-Prompting

A while loop that continues until valid input is received is the standard pattern in Python for interactive validation.
5

Keep Validation Separate

Write validation logic in its own block or function so your main program logic stays clean and readable.
✦ KEY TAKEAWAY
Think of input validation like a bouncer at the door of a concert. The bouncer checks your ticket before you enter—not after you're already inside causing chaos. Your validation code should sit right at the entrance of your program, checking every piece of data before the main logic ever touches it.

Visual Explanation — The Validation Loop

The most common pattern for input validation in Python is the validation loop. This is a while loop that keeps asking the user for input until they provide something that passes all checks. The diagram below shows the flow of a typical validation loop that checks whether the input is numeric and within a valid range.

This flowchart shows the two-stage validation pattern: first check the type (are all characters digits?), then check the range (is the number between the minimum and maximum?). If either check fails, an error message is printed and the loop sends the user back to the prompt.

Notice that the loop has two possible exit paths—both leading back to the prompt. The program only moves forward (to the green "VALID" box) when both checks pass. This layered approach ensures that you never try to convert a non-numeric string to an integer (which would crash your program) and that you never accept a number outside the expected range.

How It Works — Python Validation Techniques

Python provides several built-in tools for checking user input. The input() function always returns a string, even if the user types a number. This is the key fact that makes validation necessary: before you can treat a value as a number, you must confirm it actually represents one.

Technique 1 — Checking for Digits with .isdigit()

The string method .isdigit() returns True if every character in the string is a digit (0–9) and the string is not empty. It returns False otherwise. This is your first line of defense when you need an integer from the user.

DIGIT CHECK PATTERN
while not user_input.isdigit(): # re-prompt
This loop continues as long as the string contains any non-digit characters. Once .isdigit() returns True, you can safely call int(user_input).

Technique 2 — Range Validation

After confirming the input is numeric, you convert it to an integer and check whether it falls within an acceptable range. Python's chained comparison syntax makes this elegant.

RANGE CHECK PATTERN
if low <= number <= high: # valid range
Here, low is the minimum acceptable value and high is the maximum. Python evaluates both comparisons and returns True only if both are satisfied.

Technique 3 — Allowed Choices with in

When the user must pick from a menu—such as "A", "B", or "C"—you can store the valid options in a list or tuple and use the in keyword to check membership.

CHOICE CHECK PATTERN
if choice in ["A", "B", "C"]: # allowed
The in operator returns True if choice matches any element in the list. Tip: use .upper() or .lower() to make the check case-insensitive.

Technique 4 — try/except for Robust Conversion

For inputs that could include negative numbers or decimals (where .isdigit() would fail), you can wrap the conversion in a try/except block. If int() or float() raises a ValueError, the except block catches it and lets you display a friendly message instead of a crash.

TRY/EXCEPT PATTERN
try: number = int(user_input) except ValueError: print("Not a valid number.")
This approach handles negative numbers (like -5) and prevents crashes from letters or symbols. It is the most flexible validation technique.

Validation Patterns Classified

Now that you know the individual techniques, let's see how they combine into complete validation patterns. The diagram below classifies the three main categories of validation you'll use in Python programs: type validation, range validation, and choice validation.

The three validation categories map to different Python tools. Type validation uses string methods or try/except. Range validation uses comparison operators. Choice validation uses the in keyword. The combined example at the bottom shows type and range validation working together.
Common validation tools in Python
Validation TypePython ToolUse When…
Digit check.isdigit()You need a positive whole number from the user
Alpha check.isalpha()You need letters only, such as a name
Numeric conversiontry/except int()You need integers that may be negative
Range checklow <= x <= highThe number must fall within min and max bounds
Choice checkx in allowed_listThe user must pick from a fixed set of options

Worked Example — Movie Rating Validator

Let's build a complete program that asks the user to rate a movie on a scale of 1 to 5 stars. The program must reject non-numeric input and values outside the 1–5 range, and it should keep asking until a valid rating is received.

Movie Rating Validator
1
Step 1 — Prompt the userWe use input() to get the rating as a string. Remember, input() always returns a string.
rating_str = input("Rate this movie (1-5): ")
2
Step 2 — Set up the validation loopWe create a while loop that continues as long as the input fails our checks. We use a helper variable valid = False to control the loop.
valid = False while not valid:
3
Step 3 — Check if input is all digitsInside the loop, we first check rating_str.isdigit(). If it returns False, we print an error message explaining that only numbers are accepted and re-prompt the user.
if not rating_str.isdigit(): print("Please enter a number.")
4
Step 4 — Check the range (1–5)If the digit check passes, we safely convert to an integer and check whether the value is between 1 and 5, inclusive. If not, we print a different, specific error message.
elif not (1 <= int(rating_str) <= 5): print("Rating must be 1 through 5.")
5
Step 5 — Accept valid input and exit the loopIf both checks pass, we set valid = True so the while loop stops. After the loop, we convert the string to an integer one final time and use it.
else: valid = True rating = int(rating_str) print(f"You gave it {rating} star(s). Thanks!")
6
Step 6 — Complete programHere is the full program assembled. Note how the re-prompt sits at the bottom of the loop so it runs every time the loop cycles.
rating_str = input("Rate this movie (1-5): ") valid = False while not valid: if not rating_str.isdigit(): print("Please enter a number.") elif not (1 <= int(rating_str) <= 5): print("Rating must be 1 through 5.") else: valid = True break rating_str = input("Rate this movie (1-5): ") rating = int(rating_str) print(f"You gave it {rating} star(s). Thanks!")
💡 Why specific error messages?
Notice that we print different messages for different failures: "Please enter a number" vs. "Rating must be 1 through 5." This tells the user exactly what went wrong so they can fix it. A generic "Invalid input" is much less helpful.

Comparing Validation Approaches

There are multiple ways to write validation code in Python. Each approach has strengths and limitations. The table below compares the most common techniques so you can pick the right one for each situation.

Comparison of validation approaches in Python
ApproachStrengthsLimitations
.isdigit() checkSimple and readable; no risk of crashing; works for positive integersCannot handle negative numbers, decimals, or floats
try/except blockHandles negatives and floats; catches any conversion error; very flexibleSlightly more complex syntax; students must learn exception handling
Boolean flag (valid = False)Clear loop control; easy to add multiple checksExtra variable to track; slightly more lines of code
while True with breakCompact; avoids needing a flag variableCan be harder to read if there are many checks; easy to forget the break
Custom functionReusable; keeps main code clean; professional styleRequires understanding of functions (parameters, return values)
✦ KEY TAKEAWAY
Choosing a validation technique is like choosing the right tool from a toolbox. A screwdriver works great for screws but not for nails. Use .isdigit() for simple positive-integer checks, and reach for try/except when you need to handle negatives, decimals, or more complex conversions. As you gain experience, you'll start writing reusable validation functions.

Connection to Advanced Concepts

The validation skills you're learning now form the foundation for more advanced programming techniques. In later courses and real-world projects, you will encounter more sophisticated ways to validate data, but the core principles remain identical.

From beginner validation to advanced techniques
What You Learn NowWhere It Leads
.isdigit() and in checksRegular expressions — powerful pattern matching for email addresses, phone numbers, and more
try/except ValueErrorFull exception handling — catching multiple exception types, creating custom exceptions, and using finally blocks
Range and choice checkingData validation libraries — tools like Pydantic and WTForms that validate complex data structures automatically
Printing error messagesGUI and web form validation — showing inline errors in text fields, highlighting invalid fields red, and disabling submit buttons
Preventing crashes from bad inputSecurity hardening — defending against SQL injection, cross-site scripting (XSS), and buffer overflow attacks

The mindset of "never trust user input" is one of the most important habits you can develop as a programmer. Whether you're building a simple console app or a production web application, every piece of data that enters your system from the outside should be treated as potentially dangerous until proven otherwise. Master these basics now, and the advanced tools will feel like natural extensions of what you already know.

Practice Problems

PROBLEM 1 — CONCEPTUAL
Explain in your own words why input() always returns a string, even when the user types a number like 42. Why does this matter for input validation?
PROBLEM 2 — BASIC CALCULATION
Write a short Python code snippet that asks the user for a number between 1 and 10. If the user types something that isn't a digit, print "Not a number." If the number is outside the range, print "Out of range." Use .isdigit() for the type check.
PROBLEM 3 — INTERMEDIATE
A pizza ordering program lets the user choose a size: S, M, or L. Write a validation loop that accepts upper or lowercase input (e.g., both "s" and "S" should work). If the choice is invalid, print "Invalid size. Choose S, M, or L." and re-prompt. After valid input, print the chosen size in uppercase.
PROBLEM 4 — APPLIED
You are building a simple ATM program. The user must enter a withdrawal amount that is: (1) a valid integer, (2) positive, (3) a multiple of 20 (ATMs only dispense $20 bills), and (4) no greater than $500. Write the complete validation code using try/except. Print specific error messages for each failure case.
PROBLEM 5 — CRITICAL THINKING
Consider this code: x = input("Enter a number: ") while not x.isdigit() or not (1 <= int(x) <= 100): print("Invalid!") x = input("Enter a number: ") A student claims this code has a hidden bug. They say that if the user types "abc", Python will crash on int(x) in the while condition. Is the student correct? Explain why or why not, referencing how Python evaluates or expressions.

Lesson Summary

Input validation is the practice of checking user-supplied data before your program processes it. Since Python's input() function always returns a string, you must verify the data's type before converting. Use .isdigit() for positive integer checks, try/except for more flexible numeric conversion, chained comparisons like low <= x <= high for range validation, and the in keyword to check against a list of allowed choices.

The standard pattern is a while loop that re-prompts the user until valid input is received, printing specific, helpful error messages for each type of failure. Always validate type first, then value. Normalize input with .upper() or .lower() for case-insensitive choice validation. These foundational skills connect directly to regular expressions, exception handling, web form validation, and cybersecurity in more advanced courses.

Varsity Tutors • Computer Programming 1 (Python) • Input Validation