Errors, Validation, and Debugging · practice
Inspect Values Before Guessing
Logic bugs do not produce a
Suppose a command is not recognized:
raw_choice = " START "
choice = raw_choice.lower()
if choice == "start":
print("Starting")
else:
print("Unknown command")
You might guess that lower() is broken, or that the comparison is wrong. A temporary diagnostic print gives better evidence:
print(f"raw: >{raw_choice}<")
print(f"cleaned: >{choice}<")
The visible markers reveal spaces around the text:
raw: > START <
cleaned: > start <
The letters changed case, but the spaces remained. Now the next change is justified: strip surrounding whitespace as part of cleaning.
Useful things to inspect
During debugging, print:
a
with a label; delimiters around
so whitespace is visible; type(value)when a type assumption may be wrong;values before and after a transformation;
values immediately before a failing
or calculation.
For example:
print("quantity:", quantity)
print("quantity type:", type(quantity))
A descriptive label matters. A
Keep diagnostics temporary
Diagnostic output is for investigation, not part of the program’s promised result. Once the cause is repaired:
run the program and confirm the fix;
remove the temporary prints;
run again to confirm the final output is clean.
You can also use Step in an editor exercise to watch
Test an assumption, do not decorate a guess
Every diagnostic should answer a question:
Does this string still contain spaces?
Is this value an integer or a string?
Which branch did the condition choose?
What are the operands before the calculation?
If a print does not help distinguish possible causes, choose a more focused one.
Why are > and < useful around a string in a diagnostic print?
Task
The starter program should accept the prepared command despite its capitalization and surrounding spaces. It currently rejects it.
First run the program with the two diagnostic lines. Use their output to identify what the cleaning step missed. Then:
repair the cleaning
; remove both temporary diagnostic prints;
run again.
The final output must contain only:
Command accepted.
After it works, use Step on your completed code to watch raw_code and clean_code receive their values.