VMware ESXi and vSphere Cluster Management
Types of Errors in Python: Syntax, Runtime, and Logic Errors
Learn to identify and fix Python syntax errors, runtime exceptions, and logical errors by reading diagnostics, tracebacks, and test results.
An error is a defect or invalid situation that prevents a program from working as intended. Python errors can appear before execution starts, while the program is running, or after the program finishes when its result is wrong.
Python reports many problems with a syntax diagnostic or a traceback. A syntax diagnostic describes invalid Python structure. A traceback shows the sequence of calls and source locations that led to an unhandled exception.
How Python processes a program
In the usual beginner workflow, Python first reads and parses source code to check whether it follows Python's grammar. The interpreter implementation then commonly compiles it to bytecode, an intermediate instruction representation, before executing it. Implementation details differ between Python implementations, but the practical distinction remains useful: syntax problems are found before the affected code can run, while runtime problems occur during execution.
- Parsing: Python checks the structure and grammar of the source code.
- Execution: Python evaluates statements, expressions, functions, input, and calculations.
- Result checking: You determine whether the output and behavior match the intended rules.
| Category | When it is detected | Does execution begin? | Typical Python report | Example | Typical fix |
|---|---|---|---|---|---|
| Syntax error | While Python parses the source | Normal execution of the file cannot begin | SyntaxError diagnostic with a line, caret, and message | Missing colon after an if statement | Correct the Python grammar or structure |
| Runtime error / exception | While statements are executing | Yes | Traceback ending with an exception type and message | Dividing by zero | Validate data, correct the operation, or handle the exception |
| Logical error | When you test or inspect the result | Yes | Often no Python error report | Using the wrong comparison or formula | Check the intended rule and correct the logic |
These categories are useful for learning, but they are not perfectly exhaustive. Terminology can vary by language and teaching context. Warnings are also different from errors: a warning may point out a potential problem without stopping execution.
Syntax errors
A syntax error occurs when source code violates Python's grammatical rules. Python normally detects this while parsing the file, before normal execution begins. A file containing a syntax error cannot proceed normally until the invalid syntax is corrected.
Common syntax mistakes
- Leaving out the colon after a compound statement such as
if,elif,else,for,while,def,class,try, orexcept. - Using unmatched parentheses, brackets, or braces.
- Leaving a quotation mark unmatched.
- Using invalid or inconsistent indentation.
- Misspelling a Python keyword, such as writing
elsinstead ofelse.
Example: a missing colon
This program asks for an integer and intends to report whether it is even or odd:
number = int(input('Enter an integer: '))
if number % 2 == 0
print('Even')
else:
print('Odd')
The if line needs a colon at the end. A command such as python even_odd.py may produce a diagnostic similar to this:
File "even_odd.py", line 3
if number % 2 == 0
^
SyntaxError: expected ':'
Read the report as follows:
- File name:
even_odd.pyidentifies the source file. - Line number:
line 3identifies the reported source location. - Source line: Python displays the line it was processing.
- Caret marker:
^shows where Python noticed the problem. - Exception or diagnostic name:
SyntaxErroridentifies the category. - Message:
expected ':'suggests what structure is missing.
The caret marks where Python recognized that the syntax was invalid. The actual mistake can sometimes be earlier on the same line or on the preceding line. For example, an unmatched quote or parenthesis may cause Python to point at a later line where the parser finally becomes unable to continue.
Corrected even-or-odd program
number = int(input('Enter an integer: '))
if number % 2 == 0:
print('Even')
else:
print('Odd')
The modulo operator, %, gives the remainder after division. An integer whose remainder after division by two is zero is even. This version has valid syntax and can begin executing.
Runtime errors and exceptions
A runtime error occurs after execution has started. Python generally represents runtime errors as exceptions. An exception is both a Python object and a control-flow event that signals an abnormal condition, such as invalid input or an impossible operation.
If no code handles an exception, the current flow stops and Python displays a traceback. A traceback is a report of the calls and source locations leading to the unhandled exception.
How to read a traceback
Read a traceback from the bottom upward:
- Start with the final line. Identify the exception type and its message.
- Find the source file and line shown immediately above it.
- Inspect that line and nearby lines, including the values and types involved.
- Move upward through earlier calls if the reported line is inside a function called by other code.
For example, this code attempts to divide by zero:
numerator = 10
denominator = 0
print(numerator / denominator)
After correcting the accidental leading space before denominator, a traceback may look like this:
Traceback (most recent call last):
File "divide.py", line 3, in <module>
print(numerator / denominator)
~~~~~~~~~~^~~~~~~~~~~~~
ZeroDivisionError: division by zero
The important first clue is the bottom line: ZeroDivisionError with the message division by zero. The relevant source location is divide.py, line 3.
Common beginner exceptions
| Exception | Typical cause | Minimal example scenario | How to prevent or fix it |
|---|---|---|---|
ZeroDivisionError | Division or modulo uses a zero divisor | total / count when count is zero | Check the divisor before the operation or handle the exception |
ValueError | A value has suitable general type but unsuitable content | int('hello') | Validate the text and request a valid number; optionally catch the exception |
NameError | Code refers to a name that has not been defined | print(total) before assigning total | Define the name, correct its spelling, or check its scope |
TypeError | An operation or function receives incompatible types | 'age: ' + 20 | Convert values deliberately or use an operation suitable for their types |
IndexError | A sequence position is outside the valid range | items[3] when items has three elements | Check the sequence length and use valid indexes |
KeyError | A dictionary lookup requests a missing key | person['email'] when that key is absent | Check membership or use a suitable default such as get() |
Case study: division by zero
Consider a calculator that reads two numbers and divides the first by the second:
numerator = float(input('Numerator: '))
denominator = float(input('Denominator: '))
result = numerator / denominator
print('Result:', result)
A run with 10 and 2 succeeds and prints Result: 5.0. A run with 10 and -4 also succeeds and prints Result: -2.5.
A run with 10 and 0 reaches the division expression during execution and raises ZeroDivisionError. Division by zero is undefined for ordinary Python numeric values: there is no finite number that, multiplied by zero, produces a nonzero numerator.
Prevent the error with input validation
Input validation means checking user-provided data before using it. Since zero is a predictable invalid divisor, validate it before division:
numerator = float(input('Numerator: '))
denominator = float(input('Denominator: '))
if denominator == 0:
print('The denominator must not be zero.')
else:
result = numerator / denominator
print('Result:', result)
Validation keeps the normal program path clear and is a good choice when the invalid condition is expected and easy to test.
Handle the exception when appropriate
try:
numerator = float(input('Numerator: '))
denominator = float(input('Denominator: '))
print('Result:', numerator / denominator)
except ZeroDivisionError:
print('The denominator must not be zero.')
except ValueError:
print('Enter numeric values.')
Use try and except when an operation can fail and the program has a useful recovery path. Validation is often clearer for a simple known rule; exception handling is useful when failure can arise from several operations or from data supplied by another component.
Syntax, runtime, and logical errors
Logical errors: valid code with the wrong result
A logical error is a mistake in the program's rules, formula, condition, or control flow. The source is valid, execution completes, and Python may raise no exception. You discover the problem by comparing the output with the intended behavior.
For example, this program runs but uses the wrong comparison for an even number:
number = int(input('Enter an integer: '))
if number % 2 == 1:
print('Even')
else:
print('Odd')
For an input of 4, the program prints Odd, even though the correct result is Even. The fix is to use number % 2 == 0. Tests with known values such as 0, 1, 2, and negative integers can expose this kind of mistake.
Running small tests
Run a source file from a terminal with:
python filename.py
This is where syntax diagnostics and unhandled exception tracebacks usually appear. You can also start an interactive Python session with:
python
Use the interactive prompt to test small expressions immediately:
>>> 10 / 2
5.0
>>> 10 / 0
Traceback (most recent call last):
...
ZeroDivisionError: division by zero
A beginner debugging process
- Read the final exception type and message. It often tells you what kind of value or operation caused the failure.
- Find the indicated source line. Inspect that line and nearby lines, because the reported location is not always where the original typo occurred.
- Reproduce the issue with the smallest relevant input. For example, test a divisor of zero separately from the rest of a calculator.
- Check types, values, conditions, and edge cases. Ask whether a string needs conversion, whether a name was assigned, and whether an index or key exists.
- Fix one issue at a time and rerun the program. This makes it clear which change affected the result.
- Use descriptive variable names and small test cases. Names such as
denominatorcommunicate more than names such asx.
Common troubleshooting patterns
- SyntaxError points at an if statement: check for the required colon, matching parentheses, and matching quotation marks. Inspect the preceding line if the displayed line appears valid. Correct the structure and rerun the file.
- ZeroDivisionError follows user input: identify the division expression in the final traceback line, inspect the divisor, and test both zero and nonzero values. Reject zero before dividing or handle
ZeroDivisionError. - ValueError occurs in int() or float(): inspect the actual input for letters, blank text, or unexpected formatting. Test valid and invalid inputs, then request valid input again or handle
ValueError. - The program runs but gives an unexpected answer: create known input/output cases, print intermediate values, and verify every condition and calculation against the intended rule. Correct the logic and retain edge-case tests.
Summary
- Syntax errors violate Python grammar and are detected while source code is parsed.
- Runtime errors happen after execution starts and are commonly represented as exceptions.
- An unhandled exception stops the current flow and produces a traceback.
- Read tracebacks from the bottom upward: identify the exception type and message first, then inspect the indicated source line.
- Logical errors allow a program to run but cause incorrect results or behavior.
- Validation, small tests, descriptive names, and one-change-at-a-time debugging make errors easier to fix.
Next, continue with Python error categories and debugging practice.