Python online course

Types of Errors in Python: Syntax and Runtime Errors

Learn how Python syntax and runtime errors differ, read error messages and tracebacks, and troubleshoot examples such as a missing colon and division by zero.

What Is an Error in Python?

An error is a defect or invalid situation that prevents a program from operating as intended. An error may stop a program completely, or it may cause an operation to fail unexpectedly.

When Python reports an error, its output commonly includes the script's file name, a line number, an indication of the relevant source location, an error or exception name, and a message describing the immediate problem.

The timing of the failure is important. Some errors are found before normal execution begins, so the program never starts. Other errors happen after execution has begun, when Python reaches a problematic operation.

The Two Primary Error Categories

This lesson focuses on compile-time errors and runtime errors.

Compile-time errors

A compile-time error is detected while Python is parsing and preparing source code before normal execution begins. Python normally compiles source code into bytecode, an intermediate form, before executing it. It does not normally compile Python directly into machine code.

For beginners, a missing punctuation mark or invalid arrangement of keywords is a common compile-time problem. The program cannot start until the source code is corrected.

Runtime errors

A runtime error occurs after execution has started, when Python performs an operation that cannot be completed. The source can be syntactically valid, yet a particular value, input, or program state can still cause failure.

A runtime error is represented by an exception, which is a named runtime error event. If the exception is not handled, Python interrupts the program and prints a traceback. The traceback is a diagnostic report showing the call path, the line where execution failed, and the exception type.

CategoryWhen Python Detects ItDoes the Program Start?Typical ExampleTypical Message
Compile-time errorBefore normal execution, while Python parses or prepares the codeNoMissing colon after an if conditionSyntaxError
Runtime errorWhile an already-started program is executingIt may start and then stopDividing by zeroZeroDivisionError

Compile-Time Errors and Syntax Errors

Syntax is the grammar and punctuation rules required for valid Python code. A SyntaxError means that Python cannot interpret the source according to those rules.

For example, an if statement must end its condition with a colon. This program is missing that colon:

number = int(input("Enter an integer: "))

if number % 2 == 0
    print("The number is even.")
else:
    print("The number is odd.")

Running this file, perhaps with python error.py, produces output similar to:

  File "error.py", line 3
    if number % 2 == 0
                      ^
SyntaxError: expected ':'

The exact caret position and wording can vary between Python versions, but the important parts are consistent:

  • Source file: error.py identifies the file being processed.
  • Line number: line 3 identifies the line Python was examining.
  • Indicated position: the caret points near the location where Python detected the problem.
  • Error type: SyntaxError identifies invalid Python grammar or punctuation.
  • Message: expected ':' explains the immediate problem.

Because this is detected before normal execution, Python does not run the input statement or print either result. Correct the syntax before trying to run the program again.

Corrected odd-or-even program

Adding the colon creates a valid conditional structure. The modulo operator, %, gives the remainder after division. An even integer has a remainder of zero when divided by two.

number = int(input("Enter an integer: "))

if number % 2 == 0:
    print("The number is even.")
else:
    print("The number is odd.")

For example, entering 8 prints The number is even., while entering 7 prints The number is odd..

Runtime Errors

Runtime errors happen when Python reaches a problematic operation during execution. A program can pass Python's syntax checks and still fail because of the data it receives or the operation it attempts.

Consider a program that reads two floating-point values, divides the first by the second, and displays the result:

first = float(input("Enter the first number: "))
second = float(input("Enter the second number: "))

result = first / second
print("Result:", result)

Run it from a terminal with:

python error1.py

If the inputs are 12 and 4, the program prints:

Result: 3.0

If the second input is 0, Python reaches the division expression and raises ZeroDivisionError. The program is syntactically valid and has already started; the failure depends on the value entered at runtime.

Enter the first number: 12
Enter the second number: 0
Traceback (most recent call last):
  File "error1.py", line 4, in <module>
    result = first / second
             ~~~~~~^~~~~~~~
ZeroDivisionError: float division by zero

The traceback shows the operation that failed and the exception name. Execution stops at that operation unless the program handles the exception or prevents the invalid division.

Preventing a zero-divisor failure

A simple introductory solution is to check the denominator before dividing:

first = float(input("Enter the first number: "))
second = float(input("Enter the second number: "))

if second == 0:
    print("The second number must not be zero.")
else:
    result = first / second
    print("Result:", result)

This check does not change the fact that the original failure was a runtime error. It prevents Python from attempting the invalid operation for that input.

How to Read Python Error Output

When an error appears, start with the final lines and then inspect the referenced source line. The final line usually gives the most useful exception name and message.

Output ElementWhat It Tells You
File nameWhich script contains the reported problem
Line numberWhere Python was examining or executing code when it detected the problem
Highlighted source location or caretThe expression, token, or nearby position that Python identified
Exception or error nameThe category of failure, such as SyntaxError or ZeroDivisionError
MessageAdditional information about the immediate problem
  1. Locate the exception or error name, such as SyntaxError or ZeroDivisionError.
  2. Open the referenced file and inspect the reported line.
  3. Look at the operation identified by the message. For division errors, inspect the denominator; for syntax errors, inspect punctuation and structure.
  4. Check the lines immediately before the reported location too. For syntax issues, the actual cause can be just before the highlighted position. For example, a missing colon at the end of a condition may be indicated near the next line or token.
  5. Correct the code or input condition, then run the script again.

Troubleshooting Common Failures

“The program will not start and reports SyntaxError.”

The likely cause is that a statement does not follow Python grammar. A missing colon after an if condition is one example.

  1. Read the reported file and line number.
  2. Inspect required punctuation, parentheses, quotation marks, indentation, and keywords near that line.
  3. Check the preceding line if the highlighted position seems correct.
  4. Add the required colon and ensure the following block is properly indented.
  5. Run the script again.

“The program starts but stops with ZeroDivisionError.”

The likely cause is that the divisor supplied to a division expression is zero.

  1. Find the division expression in the traceback.
  2. Check the value used as the denominator.
  3. Reproduce the problem by entering zero as the second number.
  4. Require a nonzero divisor before performing the division, or later learn to handle the exception with try and except.

Key Points to Remember

  • A compile-time error is found while Python parses or prepares code, so normal execution does not begin.
  • SyntaxError is a common compile-time error caused by invalid Python grammar or punctuation.
  • A runtime error happens after execution has begun and may depend on input values.
  • ZeroDivisionError occurs when a division operation uses zero as its denominator.
  • An unhandled runtime exception prints a traceback and interrupts the program.
  • The file name, line number, highlighted location, exception name, and message provide starting points for debugging.