Skip to main content

Section 2.6 Errors

45 minutes
Debugging is a normal part of coding. It can be frustrating at times, but you will get better at it with practice! Watch the following video to see that all coders get bugs.

Subsection 2.6.1 Correcting Errors

Essential Knowledge 2.6.1 2.6.A.1.

Errors are a normal part of programming. As programmers develop code, they repeatedly encounter errors, identify their cause, and revise the program to correct them.
One of the first documented computer bugs was discovered by an early computer science pioneer Grace Hopper, and it was a moth that flew into a panel of a large computer in 1947! Grace Hopper debugged the computer and pasted the actual bug in her logbook.
Figure 2.6.2. Grace Hopper’s log showing a real bug, 1947.

Essential Knowledge 2.6.3 2.6.A.2.

Programmers often discover errors through user testing or feedback, such as when users receive confusing messages, see inconsistent results, or cannot complete a task. Programmers use observations of what the user did and what the app displayed to clarify what the behavior should be for the user. To fix the error, they try to reproduce it by following the same user actions and inputs, which helps confirm the cause and verify that the correction solves the real user problem.
Everyone who codes encounters bugs or errors in their programs. Sometimes the user of your program will report the problem and the programmer will have to figure out what went wrong.

Essential Knowledge 2.6.4 2.6.A.3.

Knowing common types of errors helps programmers diagnose problems more quickly and choose effective strategies to fix them when they occur.

Essential Knowledge 2.6.5 2.6.A.5.

A syntax error occurs when the code breaks the rules of the programming language, preventing the program from running as written.
When you are coding, the most common type of error is a syntax error, which means that you didn’t write the Python code correctly. For example, if you forget to close a parenthesis or use the wrong indentation, you will get a syntax error reported by the Python interpreter.
The Python interpreter tries to run your code, but if your code has syntax errors, you will see error messages displayed below the code. The error messages will tell the line number of the error and the type of error. The error messages are not always easy to understand and sometimes the actual error is before the line reported, but that is where the interpreter crashed on your code. Try to debug the code below. Read the error messages underneath to help you. Here are some common syntax errors to look for:
  • Check for missing or extra parentheses, brackets, or quotation marks.
  • Check for missing colons at the end of a line that starts a new block of code.
  • Check for incorrect indentation.
  • Check for misspelled keywords or variable names.

Essential Knowledge 2.6.6 2.6.A.7.

Programmers use error messages to identify and correct problems because they describe what went wrong and often point to where it occurred. They may include the type of error, such as syntax or runtime, the line or location in the code, and details about the operation or value that caused the problem. Programmers use error messages to decide what to check first, make a targeted change, and then rerun the program to confirm the error is resolved.

Activity 2.6.1.

Debug the code below. Read the error messages underneath to help you.

Essential Knowledge 2.6.7 2.6.A.4.

A logic error occurs when the program runs but produces incorrect or unexpected behavior because the algorithm or reasoning is incorrect.
Some errors cannot be detected by the interpreter. These are called logic errors or run-time errors. Logic errors occur when the program runs, but the output is not what you expected. For example, a programmer might have made a math mistake so the wrong value is calculated. Logic errors can be detected by testing the program with specific data to see if it produces the expected outcome.

Activity 2.6.2.

The following code has a logic error. It is supposed to calculate the average of three scores. Try running it and you will see that it does not give the correct answer. Fix the math operator in the code to correct the logic error and run to test.

Essential Knowledge 2.6.8 2.6.A.6.

A runtime error occurs while a program is executing when it encounters a situation it cannot handle, such as dividing by zero. Runtime errors may cause a program to stop running unless the error is handled. Programming languages define the specific runtime errors they produce.
Run-time errors occur when the program is running by something unexpected, such as dividing by zero or trying to read from a file that doesn’t exist.

Activity 2.6.3.

Run the following code to see the run-time error of dividing by zero (which is not allowed). Fix the code to correct the run-time error and run to test.

Essential Knowledge 2.6.9 2.6.A.8.

Programmers trace a program’s execution to determine how variable values change and which statements execute. They may trace manually or use debugging tools that step through code and display current variable values. Tracing helps identify where a program’s behavior differs from what was expected and is especially useful for finding logic errors. It can also be used to determine what conditions led to a runtime error.
Tracing is a great way to debug code, especially with logic or runtime errors. To trace code, pretend you are the computer and go through each line of code step by step, keeping track of the values of variables as you go. The Code Lens button in the active code exercises can help you to debug your code. It is based on the Python Tutor website. Try using the Code Lens button or the Python Tutor tool to trace the code in the debugging exercises above.

Essential Knowledge 2.6.10 2.6.A.9.

Programmers can add output statements to temporarily display intermediate values or messages while a program runs, such as printing variable values at key points. This helps confirm which parts of the code are executing and whether variables and conditions have the expected values. By comparing the observed output to the expected output, programmers can narrow down where the program’s behavior first begins to differ from what was expected and identify the source of an error.
Another way to keep track of what is happening in your code is to add print statements to display the values of variables at key points in the program. Try it below.

Activity 2.6.4.

The following code has a logic error. The loop is supposed to total the numbers 0 through 5, but it only adds 0 through 4. Add a print statement inside the loop to display the value of the variable number at each iteration. Then run the code to see what is happening and fix the logic error.

Subsection 2.6.2 Rubber Duck and AI Tools for Debugging

If you get stuck trying to find the bugs, sometimes another pair of eyes really helps. Ask a friend if you get stuck or try explaining your code line by line to someone or even a rubber duck. Rubber duck debugging is a lot of fun!
If you don’t have a rubber duck, try a virtual AI rubber duck like the Cyber Duck chatbot or CS50 AI Chat (available with a Github account) or a duck that just squeeks!

Essential Knowledge 2.6.11 2.6.A.10.

AI tools can support programmers in interpreting error messages, explaining what a piece of code is doing, and suggesting possible causes and fixes for unexpected behavior. Programmers can describe the expected vs. actual output and share relevant code so the tool can point out likely logic mistakes or recommend ways of making the code easier to trace. AI suggestions should be verified by running the program, checking results against requirements, and using other debugging methods, since AI-generated explanations or fixes may be incomplete or incorrect.
Many programmers use Gen AI tools to help them debug their code. Some AI tools like Co-pilot are built into the IDE and can suggest code to fix errors. Other AI tools like ChatGPT or Gemini can be used to explain what your code is doing and suggest ways to fix errors. However, remember that AI tools are not perfect and can make mistakes, so it is important to verify any suggestions they provide by testing your code and checking the results.

Subsection 2.6.3 Testing and Test Cases

Essential Knowledge 2.6.12 2.6.B.1.

In the development process, testing uses defined inputs to check whether an algorithm or program produces the expected outcomes. Programmers compare actual results to expected results and use what they learn to revise the algorithm or program. A test case consists of a specific input and the expected output or behavior that should result from that input. AI tools can help suggest test cases and predict expected results, but programmers are responsible for validating expected outcomes and using test results to confirm correctness.

Essential Knowledge 2.6.13 2.6.B.2.

Programmers often derive test cases from user stories and user testing by translating real user tasks into inputs and expected outcomes, including what the user should see at each step. This helps ensure the algorithm is correct in ways that matter to users.
When testing code, programmers create test cases with specific inputs and expected outputs. They run the code with the test case inputs and compare the actual output to the expected output. If the actual output does not match the expected output, then there is a bug in the code that needs to be fixed. A test plan with a table like the one below can be used to record the testing results for a program.
Table 2.6.14. Test Cases
Test Case Input Expected Output Actual Output

Essential Knowledge 2.6.15 2.6.B.3.

An effective set of test cases includes inputs that produce different expected outputs or behaviors, including typical, boundary, and invalid cases. Boundary test cases use values at or near important limits, such as the minimum and maximum allowed inputs or decision thresholds in conditional expressions. Invalid test cases may use values just beyond the allowed range to check how the program handles likely user mistakes.
In code with selection statements, it is important to test each branch of the conditional to ensure that the program behaves correctly for all possible inputs. With loops, it is important to use boundary test cases to test the loop’s behavior at the limits of its range. Invalid test cases with inputs just beyond the limits of the conditions for selection or loops should also be tested.

Essential Knowledge 2.6.16 2.6.B.4.

Some algorithms appear correct for common inputs but fail for other inputs, so programmers test multiple cases that cover different paths through the algorithm, such as different branches of a conditional or different numbers of loop repetitions. AI tools can help identify distinct execution paths and suggest test cases for each, but programmers should confirm that the suggested tests actually reach those paths.

Essential Knowledge 2.6.17 2.6.B.5.

Testing reflects real users: people mistype, submit blanks, use unexpected values, click repeatedly, or do steps out of order. Including these inputs as test cases helps ensure the app or program responds clearly and consistently, including giving useful feedback when input is invalid.

Subsection 2.6.4 POGIL Test Plans

Work in POGIL groups to test the following programs with test plans (What is POGIL, POGIL Role Cards).
Try the code below which has some logic errors. Use the test plan in the table in the activity below to test it. After you have filled in the actual output column, you can fix the code by changing "if" to "elif" after the first "if" to chain all the conditions together.

Activity 2.6.5 Selection Test Cases.

Use the sample code below to complete the test plan in the next activity.

Activity 2.6.6 Loop Test Plan.

Subsection 2.6.5 Learning Objectives

Learning Objective 2.6.21 2.6.B.

Develop code for test cases that can be used to check the correctness of an algorithm.

Subsection 2.6.6 Vocabulary Review

Activity 2.6.7.

You have attempted of activities on this page.