Menu

Syntax and Logical Errors

Locating Errors Using Error Messages

When a program will not run, or it stops part-way through, the compiler, interpreter or IDE gives you a message and a line number. Reading these first takes you straight to the faulty line instead of searching the whole program.

An error message is the description of the problem the compiler or interpreter has found, and the line number is the place in your code it refers to. An IDE often shows the same information as a red underline, and clicking the message jumps to the line.

Reading the report

Syntax errors are reported before the program runs. The message shows the line where the compiler or interpreter could no longer make sense of the code, because a rule, or piece of grammar, of the language has been broken.

age = int(input("Age: "))
if age = 16:
    print("You can ride the go-kart")

Output:

SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='? (line 2)

In this program = has been used to test the condition, where the comparison operator == is needed. The language rules are broken, so the program never starts. Start at the line in the report and check the punctuation and spelling there and on the line above, because that is usually where the real cause sits.

Exceptions in Python

Runtime errors are reported as exceptions. Python stops at the faulty line, prints a traceback ending in the line number, and names the exception. The exception name tells you the kind of impossible operation that was attempted, which narrows down the cause before you read any code in detail.

names = ["Ava", "Ben", "Cleo"]
pick = int(input("Which name? "))
print(names[pick])

Output when the user types 3:

Which name? 3
IndexError: list index out of range (line 3)
Exception nameWhat it tells you
ZeroDivisionErrorA number was divided by zero.
NameErrorA name was used that has not been given a value, often because of a misspelling.
IndexErrorA list index is outside the positions the list actually has.
TypeErrorValues of the wrong types were combined, such as text joined to a number with +.

Go to the line the traceback names, then use the exception name to work out what went wrong on it. A logic error does not usually produce any message, so error messages point you at syntax and runtime faults.

Practise this