It's rare to write a perfect program on your first attempt. Usually, you need to run a program several times, making code changes until it does exactly what you want. Even experienced software engineers spend a great deal of time finding and fixing problems in their own (or someone else's) code. In this chapter, you will learn how to confidently identify and resolve program errors (or bugs). Let's begin by discussing several broad categories of errors.

Logic ErrorsRobot slipping on bananna peel
It is possible to write a program that has no compile-time errors, no runtime exceptions, and yet still doesn't behave properly. You may have created a logic error, which simply means your code is not doing what you want. This type of error indicates a mistake in the algorithm or program that causes it to behave incorrectly or unexpectedly.

For example, you might use the wrong logical expression in an if statement so your program does not flow correctly. You may have also written a program that simply doesn't do what the user wants (a requirements mismatch error). Or, your program may be functional but have usability problems, meaning it is too difficult to use.

Syntax Errors
When writing code, you need to follow the syntax rules of the programming language. In Python, you have already learned many syntax rules, some of which are described below.

Functions like print() are called by writing the function name, followed by opening and closing parentheses ()
Comments start with a #
String values must be surrounded by double quotes
Values are assigned to variables using the equals sign (=)
Mathematical addition is performed using the plus sign (+)
Blocks of code are identified by indenting each line in the block to the right
The "if" statement should end with a colon (:) after the logical expression
What happens when you write code that doesn't follow Python's syntax rules? Instead of your expected program output, you will see messages describing the syntax error. No doubt, you have seen a variety of syntax error messages from the programs you have written so far. Hopefully, the error messages give you enough information to fix the problem.

The example code below is supposed to get an input temperature from the user, in Fahrenheit, and will then convert and display that temperature in Celsius. If "C" is the temperature in Celsius, and "F" is the temperature in Fahrenheit, the formula for temperature conversion is:

C = (F - 32) * 5 / 9The first time you run the example, you should see the following error message:

File "code1.py", line 1
F = int(input(What is the Fahrenheit temperature?))
^
SyntaxError: invalid syntax
This helpful message tells you where the problem was detected (in the source file "code1.py" on line 1) and displays the line of code itself. Underneath the line of code, you will see a carat symbol (^) that attempts to point to the area within the line that has invalid syntax. Finally, you are told specifically that you have a "SyntaxError", so you know the line of code is not valid in Python for some reason.

The syntax error message may not contain an exact description of the problem - in this case, we are missing double quotes around the string parameter to the input() function. The carat symbol (^) may or may not point to exactly where the syntax problem starts, but Python will give you the best hint it can. With this information, you should be able to easily find and fix the problem.

Go ahead and add double quotes around the input() string parameter to fix that syntax error, and then run the program again. The code contains a second syntax error, so you should see another error message.

File "code1.py", line 3
print("Celsius temperature = ",C)
^
SyntaxError: invalid syntax
In this case, Python has detected something fishy and says the print() statement on line 3 has invalid syntax. However, that line looks great, right? Depending on the nature of the error, Python may be confused about exactly where the problem lies. A problem earlier in the code may not be identified as a syntax problem "for sure" until a little bit later.

So, if you think the initial line of code looks fine, begin looking backward or upward in your code at earlier statements. One of those earlier statements contains an error, and Python just wasn't sure about it until later. In this case, look closely at line 2. It is missing a closing parenthesis ")" within the mathematical calculation. Every opening parenthesis "(" must be matched by exactly one closing parenthesis ")".

Go ahead and add in the missing parenthesis and re-run the program. It should now work without errors! The Fahrenheit temperatures 212 and 32 should be translated to 100 and 0 degrees in Celsius.

Runtime Errors
Once you have fixed all syntax errors in your code, your program will hopefully produce the expected output and behavior. But it's still possible that your program will do strange or unexpected things when you run it. A program can follow all the Python syntax rules and still not do what you wanted.

A program that has no syntax errors but produces unexpected results when it runs is said to have a runtime error or logical error. When you see a runtime error, you have most likely written one or more statements that don't do exactly what you thought they would. Perhaps you accidentally use the wrong variable name or select the wrong comparison operator in a logical expression, or have simply written statements in the wrong order.

Runtime errors can be hard to find because you don't get any error messages that point to a particular line of code. Instead, you need to closely study your program output and figure out for yourself if the behavior is correct. Based on what you can see of the program behavior, and your understanding of the code you have written, you need to find and fix these runtime errors on your own.

Let's say you want to write a simple calculator program that will prompt the user for two numbers, divide them, and return the result. The "dividend" is the number on top, while the "divisor" is the number on the bottom.

result = dividend / divisor

Does the program below work correctly, or does it show a run-time error? Try it and see! What happens when you enter 10 for the dividend and 5 for the divisor, expecting to get 10 / 5 = 2 as the result?

Try It Now


What went wrong? Python did not catch any syntax errors, but the program still produced incorrect results. Can you find and fix the problem?

Overflow Errors
An overflow error is an error that occurs when a computer attempts to handle a number that is outside of the defined range of values. Integer data types such as a float or int can only hold numbers within a certain range. What happens when you try to store a number that is too large into a small data type? The value will overflow and produce unexpected results.

In Python, this error also occurs when a math operation results in a value that is larger than the given data type's runtime value. When these values are larger than the declared data type, the program will generate an overflow error.

Runtime Exceptions
Have you ever seen a program "crash" when you run it? Even professionally written software may have bugs that cause the program to throw up an ugly error message, freeze completely, or exit without warning. These errors can happen when program code attempts to execute some operation that is simply not valid.

When a program attempts to execute a particular statement that is invalid, Python will "raise" or "throw" an exception. An exception is a runtime error that completely halts the program. The program cannot continue, because you have asked it to do something that is simply not possible.

For example, from your math class, you probably know that it is not possible to divide any number by zero. Such an operation is invalid and has no meaningful result. However, you can easily write a Python program that attempts this division. What happens when you run the example code below?

Try It Now


While an exception message can seem unpleasant at first, it actually provides a great deal of information to help you fix the problem. Our division-by-zero example produces the following message:

Traceback (most recent call last):
File "code1.py", line 4, in
result = dividend / divisor
ZeroDivisionError: division by zero
The second, third and fourth lines each contain important clues!

File "code1.py", line 4 - this part tells you the exception happened on line 4 in source file "code1.py"
result = dividend / divisor - this part shows the actual line of code that caused the exception
ZeroDivisionError: division by zero - this part describes the type of exception
So, when an exception happens, don't be discouraged. The exception message describes exactly where in your code the problem happened and the type of problem you need to fix. With these clues, fixing the problem is often very easy.

Which of the following mistakes is a syntax error?
Select one:

a.
Failing to surround text values with opening and closing quotes

b.
Failing to match every opening parenthesis with a closing parenthesis

c.
All of these are syntax errors

d.
Leaving off the ending colon (:) after an "if" statement

Clear my choice
Question 2Not yet answered
Question text
Which of the following pieces of information is present in messages printed when Python finds a syntax error in your code?
Select one:

a.
All of these things are present

b.
A carat symbol (^) that tries to mark the location with the statement that caused the error

c.
The line number of the statement where the error was found

d.
The name of the source file where the error was found

Clear my choice
Question 3Not yet answered
Question text
If Python identifies a particular line of code as having a syntax error, where should you look to find and fix the problem?
Select one:

a.
Exactly where the carat (^) points

b.
On that line of code or earlier (above) in your source

c.
On that line of code only; it must be right there

d.
On that line of code or later (below) in your source file

Clear my choice
Question 4Not yet answered
Question text
Which of the following is the best example of a runtime error?
Select one:

a.
A missing double-quote around a string value

b.
An incorrectly written mathematical expression provides the wrong result

c.
A comment is not started with the hashtag (#) symbol

d.
A missing parentheses in the source code

Clear my choice
Question 5Not yet answered
Question text
Which of the following best describes the difference between a logical error and a runtime exception?
Select one:

a.
Logical errors produce detailed error messages, while runtime exceptions are invisible failures

b.
Runtime exceptions allow the user to correct the problem, while logical errors can't be fixed by the user

c.
An exception halts your program completely, while a logical error allows the program to continue with incorrect results

d.
A logical error is easy to find and fix, while exceptions are always difficult

The correct answers are:

Question 1: c. All of these are syntax errors
Question 2: a. All of these things are present
Question 3: b. On that line of code or earlier (above) in your source
Question 4: b. An incorrectly written mathematical expression provides the wrong result
Question 5: c. An exception halts your program completely, while a logical error allows the program to continue with incorrect results