Chapter 5, Lesson 1 Text

Chapter Five: Finding and Fixing Problems

Lesson One: Types of Errors


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 three broad categories of errors.

Robot slipping on bananna peelSyntax 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 / 9

There are a couple of syntax errors in the code below. Run it and see what kind of messages you get!

Try It Now

The first time you run the example, you should see the following error message:

  File "", line 1
    F = int(input(What is the Fahrenheit temperature?))
SyntaxError: invalid syntax

This helpful message tells you where the problem was detected (in source file "" 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 "", 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 backwards or upwards 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 parentheses ")" 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? The Python did not catch any syntax errors, but the program still produced incorrect results. Can you find and fix the problem?

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 "", line 4, in 
    result = dividend / divisor
ZeroDivisionError: division by zero

The second, third and fourth lines each contain important clues!

  • File "", line 4 - this part tells you the exception happened on line 4 in source file ""
  • 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.


Work With Me: Bug Swatter


The short program below is supposed to ask the user for the year in which they were born. Then, if the year is even, print "You are even-keeled" to the screen. If the year is odd, it should print "You have an odd sense of humor".

The program uses the modulus operator (%) to divide the year by 2 and check the remainder result. If the remainder is 0 it is an even number, and if the remainder is 1 it is an odd number.

There are three separate errors in the initial code (a syntax error, a runtime error and a runtimeexception). Can you find and fix all three problems? Click the "Show Hint" button if you need some help!

Try It Now



End of Lesson

Last modified: Wednesday, 8 May 2019, 8:43 AM