0%

Errors, Validation, and Debugging · practice

Inspect Values Before Guessing

Logic bugs do not produce a . When the final result is wrong, inspect the values that lead to it.

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 full of bare numbers is difficult to interpret.

Keep diagnostics temporary

Diagnostic output is for investigation, not part of the program’s promised result. Once the cause is repaired:

  1. run the program and confirm the fix;

  2. remove the temporary prints;

  3. run again to confirm the final output is clean.

You can also use Step in an editor exercise to watch change one statement at a time. Temporary prints are still a valuable universal technique because they work in tiny programs, , , and most runtime environments.

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:

  1. repair the cleaning ;

  2. remove both temporary diagnostic prints;

  3. 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.