Debugging strategies

Computer Science · Programming fundamentals

Question 1 of 10

0

    Which step usually comes first when debugging?

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    Embed this practice on your site or class page

    Paste this HTML into your page. Students practise right there; it is free and needs no account.

    Debugging strategies explained

    Debugging is the process of finding and fixing errors in a program. There are three main kinds. A syntax error breaks the language rules and is reported before the program runs. A runtime error, such as dividing by zero, stops the program while it runs. A logic error runs without complaint but gives the wrong answer, and it is usually the hardest to find.

    A systematic approach works better than changing code at random. First reproduce the problem and read the error message, including its line number. Then try to find the smallest input that still causes it, because a simple case is easier to reason about. Test boundary cases such as zero, negative numbers and empty lists.

    Several tools help you see what the program is really doing. Printing or logging the values of variables at key points shows where they first become wrong. A debugger lets you step through one line at a time and inspect values. Tracing by hand, with a table that records each variable after every line, is a reliable way to find a logic error.

    Worked example

    This function should return the average of a list, but it gives the wrong answer for [2, 4, 6].

    def average(nums):
        total = 0
        for n in nums:
            total = n
        return total / len(nums)
    

    Trace it with a table, starting with total = 0.

    1. n = 2: total = 2.
    2. n = 4: total = 4.
    3. n = 6: total = 6.
    4. Return 6 / 3 = 2.0. The expected answer is 4.0.

    The bug is the line total = n, which overwrites the total instead of adding to it. Changing it to total = total + n gives totals 2, 6 and 12, so the function returns 12 / 3 = 4.0.

    What you will practise

    103 multiple-choice questions (Easy, Medium, Hard). Each answer is followed by an explanation.

    Example questions

    • Debugging is:
    • A syntax error is caught:
    • A runtime error:
    • A logic error:
    • Print-debugging means:
    • Which step usually comes first when debugging?
    • A breakpoint in a debugger is:
    • Stepping over a line in a debugger means:

    …and 95 more.