Input Validation and Error Recovery
Input validation is the practice of checking user input before allowing a program to use it.
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
- input() always returns a str, even when the user types digits.
- Check 1: an empty line (line.strip() == "") is rejected first; the loop prints a message and continue goes back to input().
- Check 2: float(line) / int(line) inside try; a non-numeric line raises ValueError and the except block recovers instead of crashing.
- 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).
- 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.
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?
Reveal 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.
Tracing an Overtime Calculation
Suppose a worker records 46 hours. Determine which hours use regular pay and which hours use the overtime multiplier.
- 1Compare with the threshold
The input is greater than 40, so the overtime path is selected.
- 2Separate the hours
The first 40 hours remain regular hours. The remaining 6 hours are above the threshold.
- 3Apply the multiplier
The 1.5x multiplier is applied only to the 6 excess hours, not to all 46 hours.
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.
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.
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.
- 1Validate the range
The score is within the permitted 0.0 to 1.0 range, so it can continue to grade assignment.
- 2Check the highest threshold
The score does not reach 0.9, so the first branch is not selected.
- 3Check the next threshold
The score reaches 0.8, so the branch associated with that threshold is selected.
- 4Stop after the match
The ordered multi-branch structure assigns one outcome instead of continuing to unrelated lower branches.
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.
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 likeA worker records 46 hours, and the program treats all 46 hours as overtime.
Why it failsThe multiplier applies only to hours above 40. The first 40 hours remain regular hours.
Do this insteadSeparate 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 likeThe user enters text, but the program tries to compare that text with numeric limits.
Why it failsThe value must first be handled as a conversion problem. A range check applies after the input has become numeric.
Do this insteadUse 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 likeA score of 1.5 is sent directly into grade assignment.
Why it failsNumeric does not automatically mean valid. The score can still be outside the permitted range.
Do this insteadCheck the allowed range before assigning a grade.
Common mistake Testing only ordinary values.
What it looks likeThe program is tested with one typical score but not with 0.9, 0.8, 0.7, or 0.6.
Why it failsBoundary values reveal whether comparison operators and branch ordering route inputs correctly.
Do this insteadTest boundaries, values between boundaries, intentionally bad input, and edge cases.
Common mistake Guessing which conditional branch ran.
What it looks likeA result is unexpected, but the program is changed without checking the selected path.
Why it failsThe source of the error may be a different branch than expected.
Do this insteadTemporarily log the input and the branch selected, such as the regular-pay path, overtime path, or matched grade threshold.
Practice Trace
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
- 1Overtime logic divides at 40 hours: regular pay applies at or below the threshold, and the 1.5x multiplier applies only to hours above it.
- 2try and except provide a recovery path for non-numeric input so the program can respond gracefully instead of crashing.
- 3Range validation is separate from conversion: a value can be numeric and still be invalid because it falls outside the permitted range.
- 4Ordered if and elif branches route valid scores to one grade outcome.
- 5Boundary 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.