Lesson 4 of 12 · 28 min · Grades 9–12
Guarding bad input
A canteen app must not crash if someone types a word instead of a number. You check first: if the value looks usable, calculate; else print a clear message. That habit is defensive programming. Full Python adds try/except; the mindset starts with if.
Broken form input
Check values before you calculate.
You will be able to
- ✓ Validate before you calculate
- ✓ Give the user a next step, not a crash
Check, then act
Never trust raw input. Age 400 is not a person. Quantity 0 should trigger Restock, not a divide-by-zero later. Write the ugly cases first.
A good error message names the field and the rule: “Age must be between 5 and 19”. Empty messages waste a support desk.
try/except in full Python
When conversion can fail (int("hello")), real programs wrap it: try: n = int(text) except ValueError: print("Type a number"). This sandbox uses if to practise the same branching idea.
Do not catch Exception and ignore it. Catch the error you expect, log it, tell the human.
Words that matter
- Validation
- Checking data before using it.
- ValueError
- What real Python raises when int() cannot parse a string.
Common mistakes
Avoid: Assuming every value is already a sensible number.
Do this: Guard ranges and empty values before arithmetic.
Example program — Age gate for a science fair form
Set age to 11 and to 16.
Edit the example, press Run, then Build if you want a compile check.
build
Press Build to compile.
Your turn — Stock check
qty = 0. If qty is less than 1, print Restock, otherwise print OK.
Edit the example, press Run, then Build if you want a compile check.
build
Press Build to compile.
Self-assessment
Check your understanding before you mark the lesson complete.
Progress is stored in a browser cookie on this device.