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.

A Python coding terminal with a program flow and laptop.
Inside this lesson 10 sections 5 questions 9 figures

SECTION 1

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.

SECTION 2

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.

SECTION 3

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.

Input Validation Loop — FlowchartSTARTuser_input = input(prompt)Prompt the userIs it alldigits?NOPrint error:"Enter digits"Loop back to re-promptYESIs value inrange?NOPrint error:"Out of range"YESVALID — ContinueLegendType check (isdigit)Range check (min ≤ x ≤ max)
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.

SECTION 4

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(userinput)exceptValueError:print("Notavalidnumber.")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.

SECTION 5

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.

Three Categories of Input Validationuser_input = input()TYPE VALIDATION"Is it the right kind?"• .isdigit()• .isalpha()• try/except int()RANGE VALIDATION"Is it within bounds?"• low <= x <= high• x > 0• len(s) <= max_lenCHOICE VALIDATION"Is it an allowed option?"• x in ["A","B","C"]• x.lower() in options• x in {"yes","no"}COMBINED EXAMPLE — Age Input (1–120)age_str = input("Enter your age: ")while not age_str.isdigit() or not (1 <= int(age_str) <= 120): print("Invalid. Enter 1-120.") age_str = input("Enter your age: ")
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.
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

Common validation tools in Python

SECTION 6

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. 1

    Step 1 — Prompt the user

    We use input() to get the rating as a string. Remember, input() always returns a string.
    rating_str = input("Rate this movie (1-5): ")
  2. 2

    Step 2 — Set up the validation loop

    We 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. 3

    Step 3 — Check if input is all digits

    Inside 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. 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. 5

    Step 5 — Accept valid input and exit the loop

    If 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. 6

    Step 6 — Complete program

    Here 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.

SECTION 7

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.

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)

Comparison of validation approaches in Python

✦

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.

SECTION 8

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.

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

From beginner validation to advanced techniques

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.

SECTION 9

Practice Problems

Question 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?
Show answer
The input() function reads everything from the keyboard as text (a string) because the computer treats keypresses as characters, not numbers. The character '4' followed by '2' is just a two-character string "42" until you explicitly convert it using int() or float(). This matters because if you try to do math with a string (e.g., compare it to a number), Python will either give unexpected results or crash with a TypeError. Validation ensures the string actually contains numeric characters before you attempt the conversion.

Question 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.
Show answer
Here is a correct solution using a while loop: num_str = input("Enter a number (1-10): ") while True: if not num_str.isdigit(): print("Not a number.") elif not (1 <= int(num_str) <= 10): print("Out of range.") else: break num_str = input("Enter a number (1-10): ") print(f"You entered {int(num_str)}.") The .isdigit() check happens first so that int(num_str) is only called after we know the string is safe to convert. The break exits the loop only when both checks pass.

Question 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.
Show answer
size = input("Choose a size (S/M/L): ").upper() while size not in ["S", "M", "L"]: print("Invalid size. Choose S, M, or L.") size = input("Choose a size (S/M/L): ").upper() print(f"You chose size {size}.") The key technique here is calling .upper() immediately on the input so that both "s" and "S" become "S". Then we check membership with in ["S", "M", "L"]. This approach is called normalizing the input — converting it to a standard form before comparing.

Question 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.
Show answer
while True: amount_str = input("Enter withdrawal amount: $") try: amount = int(amount_str) except ValueError: print("Please enter a whole number.") continue if amount <= 0: print("Amount must be positive.") elif amount % 20 != 0: print("Amount must be a multiple of $20.") elif amount > 500: print("Maximum withdrawal is $500.") else: break print(f"Dispensing ${amount}. Thank you!") This example uses try/except instead of .isdigit() because the user might type a decimal or a negative sign. The continue statement skips the rest of the loop body and goes back to the prompt if the conversion fails. Each subsequent elif checks a different business rule and gives a specific error message.

Question 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.
Show answer
The student is incorrect. The code is safe because of short-circuit evaluation. When Python evaluates not x.isdigit() or not (1 <= int(x) <= 100), it checks the left side first. If not x.isdigit() is True (meaning the input is NOT digits), Python already knows the entire or expression is True, so it never evaluates the right side containing int(x). The dangerous int(x) call only runs when x.isdigit() has already confirmed the string is safe to convert. This is an important concept to understand when combining conditions.

SUMMARY

Lesson Summary

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