I started with the obvious stuff: print statements inside the loop to see if it's even executing, then check whether the termination condition is ever reachable.
Structure your answer around a systematic debugging process: reproduce the issue, isolate the problematic loop, inspect its state, and verify the fix. Emphasize using Python's built-in debugging tools (pdb, print statements, logging) and common loop pitfalls like off-by-one errors, incorrect termination conditions, and mutation during iteration. Conclude by discussing how you'd prevent similar bugs with tests and code reviews.
Pro tip: Mention that you'd add temporary assertions or logging inside the loop to track variable changes, and that you'd check if the loop condition depends on a variable modified within the loop—a classic cause of infinite loops. Also, note that you'd consider using a debugger to step through iterations rather than relying solely on print statements.
Run the script to confirm the hang or wrong output, then narrow down to the specific loop causing the issue by adding logging or using a debugger to identify the problematic section.
Use pdb or print statements to examine loop variables, conditions, and iteration counts at each step to see where behavior diverges from expectations.
Check for off-by-one errors, incorrect comparison operators, missing updates to loop variables, or mutation of the iterable during iteration.
Based on observations, hypothesize the root cause, then modify the code and re-run to see if the issue is resolved, using unit tests to validate.
Add regression tests, improve code clarity, and consider using safer constructs like for loops over while loops where appropriate to avoid similar bugs.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.