Lesson 7 of 12
Structured learning draftValidate a whole-number input in Python
A delivery form needs a positive whole-number quantity. Learn to distinguish conversion errors from values that parse successfully but break a business rule, and check both kinds of failure with repeatable examples.
Learning objectives
- Convert text to an integer and handle ValueError.
- Reject zero and negative quantities explicitly.
- Test valid, invalid and boundary inputs.
Text to a valid quantity
Text to a valid quantity: a step-by-step view of the code example.
Convert with int(); invalid integer text raises ValueError.
Accept only positive values; zero and negative integers fail this rule.
Return the accepted quantity, or None for an invalid entry.
int() converts suitable text to an integer. Conversion alone does not establish that a value is useful: '-2' parses but is not a valid order quantity. Keep the conversion handler narrow so unrelated programming defects remain visible.
def quantity(text):
try:
value = int(text)
except ValueError:
return None
return value if value > 0 else None
for sample in ['3', '0', '-2', 'three', '3.5']:
print(repr(sample), quantity(sample))| Input | Result | Reason |
|---|---|---|
| '3' | 3 | Positive integer |
| '0' | None | Outside the allowed range |
| '-2' | None | Negative quantity |
| 'three' | None | Cannot convert to an integer |
| '3.5' | None | Decimal text is not integer text |
Test and extend the rule
- Run the file with Python 3 and compare all five output lines with the table.
- Add a blank string and a value with surrounding spaces. Predict each result first.
- Add a maximum of 100 items. Test 99, 100 and 101.
- Explain why catching every exception would make debugging harder.
Common mistakes
- Catching every exception and hiding a programming defect.
- Assuming that a negative integer cannot be parsed.
- Testing only valid quantities and skipping zero or blank input.
Practice activity
Apply the lesson
Extend quantity() to allow 1–100 items. Keep the original five cases and add 99, 100, 101 and blank input. Save the output and explain which failures are conversion errors and which are range errors.
How to check your work
- Write down the expected result before running or submitting your work.
- Try a normal example, an empty or missing input, and a boundary case where the rule changes.
- Compare the actual result with your prediction. Record the smallest example that explains a difference.
- Explain one change you made and why it improved the result. Save your evidence in the lesson notes.
When you get stuck · Python
The script stops with a traceback or gives an unexpected value.
- Find the cause
- Read the exception type and message on the last line, then find the referenced line in your own file. Compare the value and type of each input with what that operation expects.
- Try this
- Reduce the failing case to a few lines. Check variable spelling, numeric conversion and file paths. Handle only the exception you expect; do not hide an unknown error with a broad except block.
- Check the fix
- Run the corrected case and a deliberately invalid input. The valid input produces the expected result; the invalid input gives a clear message or raises the documented exception.
Use this course-wide example when it fits your task. For a different failure, record the input, expected result, actual result and smallest steps that reproduce it.
Watch, pause, practise
Free video lessons
Choose the chapter that matches your task. Videos open on the original provider’s site; playback uses additional data.
CS50: programming with Python
Choose the lecture on functions, loops, exceptions, tests or files that matches your current task.
Try it yourself: Before running an example, predict its output. Try an empty input and record how the program behaves.
Source checked 2026-10-07 · Free learning material; optional certificates may cost extra.Check your understanding
Why does '-2' need a check after int() succeeds?
Lesson summary
- Handle the conversion error you expect.
- Validate the allowed range after parsing.
- Retain tests for conversion failures and range boundaries.
Sources and further reading
- Python language referencePython Software Foundation - accessed 2026-10-07
- Errors and exceptionsPython Software Foundation - accessed 2026-10-07
Personal study note
Your notes
Keep the input, expected result, actual result and what you changed. Save before leaving this lesson. Download a copy to keep it outside this browser.