TracksPractical Coding FoundationsControl FlowDebugging Control Flow Problems(10 of 11)

Debugging Control Flow Problems

Your code runs without errors, but it does the wrong thing. Welcome to logic errors — the trickiest bugs to find because the computer is doing exactly what you told it, just not what you meant.

The Print Statement Is Your Friend

When control flow goes wrong, the fastest fix is often the simplest: add print statements to see what's actually happening.

for i in range(5):
    print(f"DEBUG: i = {i}")  # See what's happening
    if i == 3:
        print("Found 3!")

These debug prints reveal the actual values at each step. You might discover your variable isn't what you expected, or your condition is never becoming True.

Off-by-One Errors

The most common loop bug is the off-by-one error — your loop runs one time too many or one time too few.

# Should this be < or <=?
for i in range(1, 10):  # Stops at 9, not 10
    print(i)

If you wanted to print 1 through 10, you'd need range(1, 11). The end value in range() is exclusive — it stops before reaching that number. This trips up everyone at first.

Common Control Flow Bugs

Wrong comparison operator: Using = (assignment) instead of == (comparison), or < when you meant <=.

Missing else case: Your if/elif chain doesn't handle all possibilities, so some inputs fall through without any action.

Infinite loops: Your while condition never becomes False, so the loop runs forever. Always check that something inside the loop changes the condition.

Condition always True or False: Sometimes a condition is written in a way that makes it impossible to ever be the other value.

Trace Through by Hand

When stuck, grab paper and trace through your code manually. Write down each variable's value at each step. This slow, methodical approach often reveals the bug faster than staring at the screen.

# Trace this: what are x and total after each iteration?
total = 0
for x in [1, 2, 3]:
    total = total + x
    print(f"x={x}, total={total}")

When to Remove Debug Prints

Once you've found and fixed the bug, remove or comment out your debug prints. Leaving them in clutters your output and can confuse you later.

See More

You need to be signed in to leave a comment and join the discussion