Before this lesson
Understand Python functions, return values and type conversion.
What you will be able to do
Distinguish conversion, range and programming errors with recoverable feedback.
Understand the mechanism
Catch failures around the operation you can meaningfully handle. Conversion and I/O failures differ; replacing every exception with zero disguises defects as valid data.
Parsing and range validation are separate. A parsed integer can still violate the rule. Compare a missing-result sentinel explicitly so a legitimate zero is not confused with failure.
Explain corrections to users while preserving diagnostics appropriately. Interactive retries need an exit path; batch processing can collect row errors for an explicit skip-or-stop policy.
Use finally for cleanup, not unconditional success. Context managers simplify resources. Retrying unchanged malformed input cannot fix the cause.
Runnable example
Use Python 3.11 or later. Save lesson.py in a separate practice directory and run python3 lesson.py, or py lesson.py on Windows. Examples use only the standard library.
def parse_minutes(raw):
try:
value = int(raw.strip())
except ValueError:
return None, "Enter a whole number."
if not 0 <= value <= 240:
return None, "Use a value from 0 to 240."
return value, ""
for raw in ["0", " 25 ", "2.5", "-1", ""]:
value, error = parse_minutes(raw)
print(repr(raw), value, error or "OK")
Trace and verify
Zero and trimmed 25 pass; decimal and empty input fail parsing, while negative one fails range validation. The function expects strings; decide explicitly whether callers must uphold that contract or the function validates broader types.
Common mistakes and boundaries
Leaving unrelated exceptions visible can expose invalid calls. Broadening the catch merely to make tests pass hides rather than solves the contract issue.
Practice challenge
Return accepted durations plus position-based error reports for a batch, preserving order.
Reference solution and reasoning
Parse each item, split on the explicit sentinel and accumulate diagnostics. The caller decides whether partial success is acceptable.