Debugging Your Logic: How to Find and Fix Mistakes When Code Runs Wrong
Learn a systematic four-step debugging workflow to track down logic bugs when your code runs without crashing but produces the wrong output.
In This Article
- Distinguish clearly between syntax errors, runtime crashes, and silent logic bugs.
- Apply the 4-step debugging loop: Reproduce, Isolate, Inspect State, and Fix & Verify.
- Recognize the four most common beginner logic mistakes in blocks, Python, and C++.
- Walk through a broken accumulator program and fix its execution order step by step.
When Your Program Runs Without Errors—And Still Gets It Wrong
Every programmer remembers the relief of finally fixing all their syntax errors, pressing run, and seeing no red error messages—only to realize the program printed 0 instead of 250, or let an invalid user log in. Why didn't the computer warn you?
Because computers have zero common sense. They do not know what your program is supposed to accomplish; they only execute the exact instructions you gave them. To become a confident programmer, you need to understand the three categories of software errors and learn a repeatable method for hunting down bugs.
The Three Types of Programming Errors
- Syntax Errors: Broken grammar rules (like a missing colon in Python or semicolon in C++). Caught immediately before the program starts.
- Runtime Errors (Exceptions / Crashes): The grammar is valid, so the program starts running, but it encounters an impossible operation midway through—such as dividing a number by zero (
ZeroDivisionError) or trying to read the 10th item of a list that only has 3 items. - Logic Errors (Semantic Bugs): The program starts, runs to completion without crashing, and prints an answer—but the answer is wrong because there is a flaw in your algorithm.
The 4-Step Debugging Loop
When your block workspace, Python script, or C++ program produces the wrong result, resist the temptation to delete everything or guess at fixes. Follow these four steps in order:
Step 1: Reproduce Consistently
Find a small, specific input that reliably triggers the wrong output. Instead of testing a loop that runs 1,000 times, shrink the loop to 3 iterations with simple numbers (like 1, 2, 3) where you can easily calculate the right answer in your head.
Step 2: Isolate Where the Bug Lives
A 20-line program has a beginning (setup), a middle (loops and conditions), and an end (output). Determine which section first goes off track. If the output at line 20 is wrong, was the data already wrong at line 10?
Step 3: Inspect State (Print / Trace Variables)
Most bugs happen because a variable does not hold the value you think it holds. Insert temporary PRINT blocks (or print() / std::cout statements) inside your loops and branches to make the invisible state of your variables visible on every step.
Step 4: Fix One Thing and Verify
Change only one thing at a time, then re-run your test case. If you change three lines at once and the output changes, you will not know which edit helped and which introduced a brand-new bug.
Four Classic Beginner Logic Bugs to Watch For
- 1. Resetting an Accumulator Inside the Loop: If you want to add up numbers across a loop, you must initialize
total = 0before the loop starts. If you accidentally placeSET total TO 0inside the loop, the program wipes out your running total on every single pass! - 2. Wrong Sequence Order: Statements execute strictly top to bottom. If you calculate
total_price = price + taxon line 1, and then settax = 5on line 2, line 1 used the old value oftax. - 3. Premature Action Inside a Loop: Putting your final summary
PRINT "Done!"or final average calculation inside the loop mouth instead of underneath the loop causes it to run on every iteration. - 4. Flipped Comparison or Boundary Condition: Using
>when you meant<, or using>instead of>=so that exact boundary values (like a score of exactly60) fail the check.
Case Study: Fixing a Broken Savings Calculator
Suppose we want a program that starts with a piggy bank balance of 0 and adds 15 dollars a week for 4 weeks, then prints the final total of 60. However, a beginner writes the buggy program below, and when it runs, it prints 15 four times in a row!
Buggy Visual Blocks
REPEAT 4 TIMES (week = 1 to 4)
SET balance TO 0
SET balance TO balance + 15
PRINT balance
Buggy Python
for week in range(4):
balance = 0
balance = balance + 15
print(balance)
Buggy C++
for (int week = 0; week < 4; week++) {
int balance = 0;
balance = balance + 15;
std::cout << balance << "
";
}
Diagnosing and Fixing the Bug
When we trace the buggy code above, we spot two structural errors right away:
- Bug #1 (Reset inside loop):
SET balance TO 0is snapped inside the C-shaped loop. On week 1,balancebecomes0 + 15 = 15. On week 2, the very first line inside the loop resetsbalanceback to0, so it becomes0 + 15 = 15again! Fix: DragSET balance TO 0above the loop so it runs only once at the start. - Bug #2 (Print inside loop): Because
PRINT balanceis inside the loop, it prints on every week instead of once at the end. Fix: Move the print statement below the loop (unindented in Python, after}in C++).
Rubber Duck Debugging and Boundary Testing
Two habits used by professional software engineers can save you hours of frustration when a logic bug refuses to show itself:
- Rubber Duck Debugging: Explain your program out loud, line by line, to an inanimate object (like a rubber duck on your desk) or a classmate. Crucial rule: you must state what each line actually says, not what you intended it to do. More often than not, halfway through explaining a loop or condition out loud, you will hear yourself say, "Wait—why am I resetting the variable right here?"
- Boundary Value Testing: Never test your code with only one "easy" middle number. Always test the edges:
0, negative numbers, an empty input, and the exact threshold number in anifstatement (such as testing exactly60when the passing rule is60 or higher). Edge cases expose off-by-one bugs immediately.
Fixed Visual Blocks
SET balance TO 0
REPEAT 4 TIMES (week = 1 to 4)
SET balance TO balance + 15
PRINT balance
Fixed Python
balance = 0
for week in range(4):
balance = balance + 15
print(balance)
Fixed C++
int balance = 0;
for (int week = 0; week < 4; week++) {
balance = balance + 15;
}
std::cout << balance << "
";
Try It Yourself
Debug the Discount Calculator: A store wants to give a $10 discount on orders of $50 or more, and then add a flat $5 shipping fee to all orders. Read the buggy code below:
order_total = 50
if order_total > 50:
order_total = order_total - 10
order_total = order_total + 5
print(order_total)
Find the Two Logic Bugs:
- Why did the customer with a $50 order not receive the $10 discount?
- Why was the $5 shipping fee skipped for this customer, and how should the indentation change so every order gets the $5 shipping fee?
Answers: (1) The condition used > 50 instead of >= 50, causing an off-by-one boundary bug for orders of exactly $50. (2) order_total = order_total + 5 is indented inside the if block, so shipping is only added when the discount applies. Unindent that line so it sits at the left margin after the if block.
CodeCracker