When writing code, even experienced programmers make mistakes. These mistakes lead to errors that can stop your program from working correctly. In Python, errors generally fall into two main categories: syntax errors and exceptions (also known as runtime errors). Understanding the difference is the first step towards writing more resilient code.
Syntax errors are problems with the structure or grammar of your Python code. Just like human languages have rules about sentence structure and punctuation, Python has rules about how code must be written. If you break these rules, the Python interpreter cannot understand your instructions.
These errors are detected before your program even starts running, during a phase called parsing. The interpreter reads your code and checks if it follows Python's syntax rules. If it finds a violation, it stops immediately and reports a SyntaxError
.
Common causes of syntax errors include:
whlie
instead of while
).:
) after if
, for
, or def
statements.()
, square brackets []
, or curly braces {}
.Let's look at an example:
# Example of a SyntaxError: Missing colon
number = 10
if number > 5
print("Number is greater than 5")
If you try to run this code, Python will stop and point out the problem before executing any of it:
File "your_script_name.py", line 3
if number > 5
^
SyntaxError: expected ':'
The error message usually tells you the file name (your_script_name.py
), the line number where the error was detected (line 3), and sometimes uses a caret (^
) to indicate the exact position of the problem. It also provides the type of error (SyntaxError
) and a brief description (expected ':'
). Because syntax errors prevent the program from starting, you must fix them before your code can run at all.
Exceptions, or runtime errors, occur while your program is executing. Unlike syntax errors, the code's structure is grammatically correct according to Python's rules. However, during execution, the program encounters an unexpected situation or an operation that cannot be completed.
When an exception occurs, Python creates an "exception object" containing information about the error. If this exception is not handled by your code, the program stops executing and prints a "traceback," which shows the sequence of function calls that led to the error and details about the exception itself.
Here are a few common types of exceptions:
TypeError
: Occurs when an operation is performed on an object of an inappropriate type. For example, trying to add a number and a string.
age = 30
message = "My age is: " + age # Trying to add string and integer
print(message)
Running this causes:
Traceback (most recent call last):
File "your_script_name.py", line 2, in <module>
message = "My age is: " + age
^~~~~
TypeError: can only concatenate str (not "int") to str
NameError
: Raised when you try to use a variable or function name that hasn't been defined yet.
print(my_variable) # my_variable was never assigned a value
Running this causes:
Traceback (most recent call last):
File "your_script_name.py", line 1, in <module>
print(my_variable)
^^^^^^^^^^^
NameError: name 'my_variable' is not defined
ValueError
: Occurs when a function receives an argument of the correct type but an inappropriate value.
number_string = "abc"
number = int(number_string) # Cannot convert 'abc' to an integer
print(number)
Running this causes:
Traceback (most recent call last):
File "your_script_name.py", line 2, in <module>
number = int(number_string)
^^^^^^^^^^^^^^^^^^^
ValueError: invalid literal for int() with base 10: 'abc'
ZeroDivisionError
: Raised when you attempt to divide a number by zero.
result = 10 / 0
print(result)
Running this causes:
Traceback (most recent call last):
File "your_script_name.py", line 1, in <module>
result = 10 / 0
~~^~~
ZeroDivisionError: division by zero
These are just a few examples; Python has many built-in exception types for various runtime errors (like FileNotFoundError
when a file doesn't exist, or IndexError
when trying to access a list element with an invalid index).
The significant difference is timing and cause: syntax errors are caught before execution due to incorrect code structure, while exceptions happen during execution because of unforeseen circumstances or invalid operations on data. While you must fix syntax errors to run your code, exceptions can often be anticipated and handled gracefully within the program itself. The following sections in this chapter will show you exactly how to manage these runtime exceptions using Python's try
, except
, else
, and finally
blocks.
© 2025 ApX Machine Learning