Concepts / Input Validation and Error Recovery

Input Validation and Error Recovery

Input validation is the practice of checking user input before allowing a program to use it.

  • Programming
Interactive lab

Try it: Validate Input Before Processing

How a program reads untrusted text with input() and checks it in order (empty line, conversion with try / except, allowed range) before it computes anything, re-prompting after each rejected line. Switch a check off, or run the range check before converting, to see which bad input slips through or crashes the program.

How it works

  1. input() always returns a str, even when the user types digits.
  2. Check 1: an empty line (line.strip() == "") is rejected first; the loop prints a message and continue goes back to input().
  3. Check 2: float(line) / int(line) inside try; a non-numeric line raises ValueError and the except block recovers instead of crashing.
  4. Check 3: a converted number outside the allowed range is still invalid and is rejected (the range check must come after the conversion: comparing the str itself raises TypeError).
  5. The first line that passes every check breaks out of the loop and is processed: overtime pay (1.5x only for hours above 40), ordered grade bands, or a ticket total.

Default run (21 steps): The overtime pay program is ready. 4 input lines are queued for input(). … print shows Pay: 475.0.

Simplified: Three fixed programs (you change the input lines and switch the checks, never the code); the lab implements their Python semantics itself and nothing is executed as Python. Every combination was run in CPython 3.12 with the same inputs and the lab reproduces its output and error messages. input() returns the lines you type, one per call (the prompt is not printed), and raises EOFError when they run out. Input is printable ASCII only.

Educational simulation

Loading the simulation…

The First Decision

Input validation is the practice of checking user input before allowing a program to use it. Error recovery adds a response for input that cannot be processed normally. These ideas become clearer when you trace the decisions in three situations: overtime pay, non-numeric input, and grade assignment. In each situation, the program must route the input to an appropriate path instead of treating every value identically.

What do you think happens?

A worker records exactly 40 hours. Should the overtime multiplier be applied?

  • Yes, to all 40 hours

  • Yes, but only to some of the hours

  • No, because overtime applies only to hours above 40

Reveal answer
Answer:

No, because overtime applies only to hours above 40

The calculation path changes only when the number of hours is greater than 40. Hours at or below the threshold follow the regular-pay path.

Overtime Thresholds

Overtime logic has two paths. When hours worked are at or below 40, the program uses the regular-pay path. When hours worked are above 40, it separates the hours into two portions: the first 40 hours remain regular hours, and only the hours above 40 receive the 1.5x multiplier. The important detail is that the multiplier does not apply to the entire number of hours.

Hours workedinputHours > 40threshold checkRegular payall hours at regular rateOvertime payexcess hours at 1.5xSeparate hours40 regular and excess hoursreadnoyesapply multiplier to excess
How does the calculation path change when hours worked are above versus at or below 40, and where is the 1.5x multiplier applied?
Worked example

Tracing an Overtime Calculation

Suppose a worker records 46 hours. Determine which hours use regular pay and which hours use the overtime multiplier.

  1. 1
    Compare with the threshold

    The input is greater than 40, so the overtime path is selected.

  2. 2
    Separate the hours

    The first 40 hours remain regular hours. The remaining 6 hours are above the threshold.

  3. 3
    Apply the multiplier

    The 1.5x multiplier is applied only to the 6 excess hours, not to all 46 hours.

Result

The calculation combines regular pay for 40 hours with overtime pay for 6 hours.

Recovering from Bad Input

A user may enter text when the program expects a number. A try block gives the program a place to attempt the numeric operation. An except block provides the recovery path when the input is non-numeric. Instead of allowing the invalid conversion to crash the program, the program catches the problem and responds gracefully.

User inputtext enteredtry conversionattempt numeric useContinue processinginput is numericGraceful recoveryrespond without crashingexcept responsenon-numeric input caughtsend inputnumericnon-numerichandle error
What happens to program control when a user enters text instead of a number, and how does execution recover without crashing?
In the real world

Imagine a pay program asking for hours worked. If the user enters the word forty instead of a numeric value, the numeric conversion cannot proceed normally. The try path is interrupted, the except path handles the non-numeric input, and the program can give a helpful response rather than crashing.

Ordered Grade Checks

Grade assignment combines range validation with multi-branch conditional logic. First, the program must determine whether the score is within the permitted range. If it is valid, ordered conditions such as if, elif, elif, and else route the score to the correct outcome. The order matters because the program checks the branches sequentially and should assign one outcome rather than allowing several thresholds to compete.

Numeric scoreinputAllowed rangerange checkInvalid scorereject or reportNext bandnext grade checkRemaining bandfinal grade outcomeHighest bandfirst grade checkcheckoutside rangeinside rangecondition falsecondition truecondition selected
How does a numeric score move through ordered grade-range checks until exactly one grade is assigned?
Worked example

Tracing a Grade Boundary

Suppose a grading policy uses thresholds at 0.9, 0.8, 0.7, and 0.6. Trace a score of 0.8 through the ordered checks.

  1. 1
    Validate the range

    The score is within the permitted 0.0 to 1.0 range, so it can continue to grade assignment.

  2. 2
    Check the highest threshold

    The score does not reach 0.9, so the first branch is not selected.

  3. 3
    Check the next threshold

    The score reaches 0.8, so the branch associated with that threshold is selected.

  4. 4
    Stop after the match

    The ordered multi-branch structure assigns one outcome instead of continuing to unrelated lower branches.

Result

The score follows the 0.8 threshold branch after the 0.9 branch is rejected.

Validation Before Processing

A reliable input path has three stages. The program reads the input, attempts to convert it to a number, and then checks whether that number is allowed. Only after those checks should the program perform a calculation or assign an outcome. This sequence prevents a non-numeric value from reaching numeric logic and prevents an out-of-range number from being treated as valid.

Read inputuser valueConvert to numbertry stepCheck allowed rangevalidation stepProcess valid valuecalculate or assigninputnumericallowed
How does input move from being read, to being converted to a number, to being checked against an allowed range before calculation or assignment?
Non-numeric inputconversion problemexcept responserecover from conversionerrorOut-of-range numbervalidation problemRange responsereject or report valuecannot convertfails range check
What is the difference between non-numeric input and a numeric value outside the permitted range, and how does the program respond to each?
Best practice

Test each branch deliberately. For overtime, test hours below 40, exactly 40, and above 40. For exception handling, test valid numeric input, invalid text, negative numbers, and very large numbers. For grading, test the thresholds 0.9, 0.8, 0.7, and 0.6, values between thresholds, and out-of-range values such as 1.5 and -0.1.

Mistakes Beginners Make

  • Common mistake

    Applying the 1.5x multiplier to every hour when the worker exceeds 40 hours.

    What it looks like

    A worker records 46 hours, and the program treats all 46 hours as overtime.

    Why it fails

    The multiplier applies only to hours above 40. The first 40 hours remain regular hours.

    Do this instead

    Separate the regular 40 hours from the excess hours before applying the multiplier.

  • Common mistake

    Treating non-numeric input as a range-validation problem.

    What it looks like

    The user enters text, but the program tries to compare that text with numeric limits.

    Why it fails

    The value must first be handled as a conversion problem. A range check applies after the input has become numeric.

    Do this instead

    Use the try path for the numeric operation and the except path for non-numeric input.

  • Common mistake

    Skipping range validation because the input was successfully converted to a number.

    What it looks like

    A score of 1.5 is sent directly into grade assignment.

    Why it fails

    Numeric does not automatically mean valid. The score can still be outside the permitted range.

    Do this instead

    Check the allowed range before assigning a grade.

  • Common mistake

    Testing only ordinary values.

    What it looks like

    The program is tested with one typical score but not with 0.9, 0.8, 0.7, or 0.6.

    Why it fails

    Boundary values reveal whether comparison operators and branch ordering route inputs correctly.

    Do this instead

    Test boundaries, values between boundaries, intentionally bad input, and edge cases.

  • Common mistake

    Guessing which conditional branch ran.

    What it looks like

    A result is unexpected, but the program is changed without checking the selected path.

    Why it fails

    The source of the error may be a different branch than expected.

    Do this instead

    Temporarily log the input and the branch selected, such as the regular-pay path, overtime path, or matched grade threshold.

Practice Trace

MEDIUM

Trace these inputs through the appropriate validation and conditional paths: 40 hours, 45 hours, text entered where hours are expected, a score of 0.9, a score of 0.65, and a score of 1.5. For each one, identify whether conversion is needed, whether range validation is needed, which conditional branch should be selected, and whether the program should calculate, assign an outcome, or recover from invalid input.

Hints
  • The overtime threshold changes the path only when hours are greater than 40.
  • Non-numeric input belongs to the exception-handling path.
  • A score should be checked against the permitted range before grade thresholds are tested.
  • Boundary values such as 0.9 deserve their own test because they reveal how a comparison is written.

Reliable Conditional Programs

  1. 1
    Overtime logic divides at 40 hours: regular pay applies at or below the threshold, and the 1.5x multiplier applies only to hours above it.
  2. 2
    try and except provide a recovery path for non-numeric input so the program can respond gracefully instead of crashing.
  3. 3
    Range validation is separate from conversion: a value can be numeric and still be invalid because it falls outside the permitted range.
  4. 4
    Ordered if and elif branches route valid scores to one grade outcome.
  5. 5
    Boundary values, edge cases, and intentionally bad input are essential tests for conditional logic.

Key Takeaways

  • Apply overtime pay only to hours above 40, using the 1.5x multiplier for the excess hours.
  • Use try and except to handle non-numeric input through a recovery path.
  • Validate numeric ranges before performing calculations or assigning outcomes.
  • Use ordered multi-branch conditions for grade assignment.
  • Test thresholds, boundaries, edge cases, and intentionally invalid input.

Related concepts

More concepts starting with I