
Python has become a primary tool for many data professionals for data manipulation and machine learning purposes because of how easy it is for people to use. The programming language has basically become the gold standard in the data community.
If you are already familiar with Python, you often encounter erroneous information whenever you produce incorrect syntax or violate Python’s rules. It is embedded in Python’s design philosophy to emphasize that errors need to be shown explicitly, following the principle that it’s Easier to Ask Forgiveness than Permission (EAFP), which allows you to execute the code first before knowing whether there’s an error.
Some Python errors are not bugs but features that help users improve their Python skills. Understanding these errors is vital if we wish to use them as guidance for our work intentionally. For learning purposes, this article will explore seven different Python errors that are features.
Let’s get into it.
1. Syntax Error
A syntax error is raised when the Python parser encounters invalid code syntax that does not follow Python logic. Any improper code will be shown as an error, which becomes fundamental to Python’s design features. Let’s see the error in the Python code.
The code above will raise a syntax error like below.
Cell In[6], line 1
if True print("hello")
^
SyntaxError: invalid syntax
The error shows that we are not adhering to Python syntax. The syntax error design is intentional because it is a Python feature that fundamentally indicates that any deviation from the standard needs to be fixed. It will not run any code that doesn’t follow the language grammar and does not try to guess what we want to do.
The syntax error ensures that we always have clear and unambiguous code. It also helps with collaboration, as the standard remains consistent regardless of where you run the Python language.
2. Index Error
For anyone using Python, there are many times when we use sequence objects such as lists or tuples for our work. Accessing data within these sequence objects will require us to use indexing methods.
Well, what happens when we access with an index outside of its bounds? Python will throw an error message. Let’s see what happens using actual code.
lst = [1, 2, 3]
print(lst[5])
The code above will throw the following error:
IndexError Traceback (most recent call last)
Cell In[2], line 2
1 lst = [1, 2, 3]
----> 2 print(lst[5])
IndexError: list index out of range
The error is shown as an index error, which notifies you that the index is out of range. The error is intentional, as it demonstrates that Python does not allow silent padding (a case where out-of-bound data access automatically extends the structure with placeholder values).
If it were to happen, the behavior would introduce subtle bugs that cause more problems in a more complex pipeline. For example, looping in a Python sequence will break the loop when the index is out of bounds, which would not happen if no Index errors were present.
3. Key Error
As we know, the dictionary object maps keys to values stored inside. Similar to an index error, a Key Error occurs for the dictionary object when the lookup fails because the key is not present in the dictionary object. Let’s see how it acts in Python code.
d = {'a': 1}
print(d['b'])
The code above will raise the following error:
KeyError Traceback (most recent call last)
Cell In[3], line 2
1 d = {'a': 1}
----> 2 print(d['b'])
KeyError: 'b'
The key error is raised because no ‘b’ key is in the dictionary. It’s by design that Python explicitly raises this error, as we do not want unintended behavior to use placeholder values for the key silently.
Using this key error, we can catch any syntax mistakes or logic errors during dictionary access instead of guessing if the key is there or not. The error is also useful when combined with the try/except syntax to create a new key in the dictionary if it is not present.
4. Name Error
Name error is an error that occurs when we call a variable that has not been defined previously. There is also a similar case called Unbound Local Error, a subclass of name error, where we have a Python function that tries to access a local variable before it is defined. Let’s see the error in the code below.
The error is shown in the output below.
NameError Traceback (most recent call last)
Cell In[5], line 1
----> 1 print(x)
NameError: name 'x' is not defined
The code raises an error because we have not defined the ‘x’ variable yet. Let’s see the Python code for the Unbound Local Error.
def foo():
x = x + 1
foo()
The error is shown in the output below.
Cell In[4], line 2, in foo()
1 def foo():
----> 2 x = x + 1
UnboundLocalError: cannot access local variable 'x' where it is not associated with a value
Both errors here are raised because we need to follow Python’s scoping rule, which states that we cannot accidentally use variables that are not present yet. The error allows users to catch typos or bugs immediately, rather than Python silently creating variables that will disturb our Python work.
5. Type Error
Type Error is an error that is raised when we perform a certain operation on an object but with the wrong object type. Let’s show the type error with the Python code below.
The error is raised as shown in the output below.
TypeError Traceback (most recent call last)
Cell In[7], line 1
----> 1 next([1, 2, 3])
TypeError: 'list' object is not an iterator
The type error occurs because we cannot pass an iterator object to the next function.
Python is designed to use objects only in their intended ways. That’s why, this error helps users prevent subtle bugs and ensures that the function works as intended.
6. Value Error
In contrast with the type error, the value error is raised if the function receives a correct type argument but an inappropriate value. Let’s show it with the Python code.
The error is shown in the result below.
ValueError Traceback (most recent call last)
Cell In[8], line 1
----> 1 int("abc")
ValueError: invalid literal for int() with base 10: 'abc'
You can see that the value error happens because we pass a string value that is not a valid number. The function receives the right type but not the proper value, so Python signals it’s an error. It’s the Python design that shows that the error is happening instead of ignoring it or putting a placeholder value, as that would disturb our work.
7. Assertion Error
An assertion error occurs when the assert statement is used and the condition is not met or is false. It’s a feature that is useful for debugging and enforcing any assumptions in your Python work. Let’s see the error with the Python code below.
assert 2 + 2 == 5, "It's not right"
You will get the following error.
AssertionError Traceback (most recent call last)
Cell In[13], line 1
----> 1 assert 2 + 2 == 5, "It's not right"
AssertionError: It's not right
The code 2 + 2 == 5
produces a False value, leading to an assertion error when we utilize the assert statement. We can always include details about the error when using assert, similar to what you see above.
The assertion error helps users provide flexibility in development, as we can set up a failure-catching system that allows for easier debugging. By selecting the conditions under which the assertion error is raised, we also gain more control over how the error should behave.
Conclusion
Many data professionals use Python. The programming language sometimes raises errors that are actually features, and so we have to keep our eyes open and inspect our traceback stack.
I hope this has helped!
Cornellius Yudha Wijaya is a data science assistant manager and data writer. While working full-time at Allianz Indonesia, he loves to share Python and data tips via social media and writing media. Cornellius writes on a variety of AI and machine learning topics.