Posted by Marta on February 2, 2023 Viewed 8473 times
Errors are inevitable when you are programming. As you write code, errors will start rising. The better you understand these errors, the easier it will be to avoid them. This article will learn the main Python errors, how to interpret them, and how they arise. For example, Python nameerror name is not defined; what does this mean? You will find out by the end of this tutorial.
The goal of an error, or exception, is flagging something unexpected happened while running the code. Some of these situations arise frequently. Therefore python contains some built-in exceptions that capture the more frequent unexpected situation. Below we will go through each of those exception types and see what’s the meaning behind.
See a list of all built-in errors in the python documentation.
This error occurs when the code you write doesn’t follow the python syntax rule. For example, not closing parenthesis will lead to a syntax error. The python parser won’t parse the code if it doesn’t follow the syntax rule. Therefore it can’t process it any further. Let’s see some examples:
Example #1
list = [1, 23, 45, 0, 9] for item in list print(item)
Output:
File line 2 for item in list ^ SyntaxError: invalid syntax
This code raised an unexpected situation because line 2 is missing the colon at the end, which breaks the python syntax rules.
Example #2
list = [1, 23, 45, 0, 9] for item in list: print(item
Output:
File line 4 ^ SyntaxError: unexpected EOF while parsing
The code above raised an error because line 3 is missing the closing parenthesis.
This error means that you are trying to do an operation on a variable of the wrong type. For example, doing an arithmetic operation between a string and an integer or concatenate a string with a number. See some examples below:
Example #1
print(4+"4")
Output:
Traceback (most recent call last): File 1 in <module> print(4+"4") TypeError: unsupported operand type(s) for +: 'int' and 'str'
The error occurs because python expects an int variable after the plus sign; however, it has found the string “4”. Since the type is wrong, the code will raise a Typeerror exception.
Example #2
abs("3")
Output:
Traceback (most recent call last): File line 1, in <module> abs("3") TypeError: bad operand type for abs(): 'str'
The code above encountered a Typeerror exception because the abs function only accepts number types, not a string. Therefore the string is incorrect as an argument, and the function raises an exception.
You will encounter a nameerror (the name is not defined) when a variable is not defined in the local or global scope. Or you used a function that wasn’t defined anywhere in your program. For example, you will see this error if you try to print a variable that wasn’t previously defined. You might also see this error when you use a built-in library, but forget to import the library first. Let’s see a few code examples:
Example #1
number = 1 print(num)
Output:
Traceback (most recent call last): File line 4, in <module> print(num) NameError: name 'num' is not defined
Usually, this error is highlighting that there is a typo in one of the variable names
Example #2
def print_age(age): print('My age is: '+str(age)) print__age(14)
Output:
Traceback (most recent call last): File line 4, in <module> print__age(14) NameError: name 'print__age' is not defined
This issue is similar to the previous example but applied to function. Although there is a “print age” function, the function name is print, underscore, and age; however, I used double underscore __ when I called the function. That’s why the code can’t find the function.
Another frequent error is the KeyError. This error has to do with dictionaries and accessing the dictionary data. You will encounter this error when you attempt to access a dictionary property, but the property doesn’t exist. See the example below:
Example #1
person_dict= { 'age':13, 'name': 'Joe'} print(person_dict['dob'])
Output:
Traceback (most recent call last): File line 2, in <module> print(person_dict['dob']) KeyError: 'dob'
You can avoid this error using the method .get()
, which will return None
if the property doesn’t exist.
person_dict= { 'age':13, 'name': 'Joe'} print(person_dict.get('dob'))
Output:
None
This error will arise when your program is importing a module that can’t be found in the list of python modules available. This error usually happens when you are using third-party libraries(not a built-in library); however, the library is not installed. See the example below:
Example #1
import pygame pygame.init() # start the game engine window_size = (640, 480) screen = pygame.display.set_mode(window_size) # create a window
Output:
Traceback (most recent call last): File line 1, in <module> import pygame ModuleNotFoundError: No module named 'pygame'
The Pygame library is a third-party library that contains functionality to create games. Since the library is not installed on my machine, I got the error above. To fix this problem, I can install the Pygame library on my laptop device using the pip
tool( Python Package Index). Once that’s done, the error will disappear.
You will find this error when you attempt to use an object field or method that doesn’t exist. Fields and methods of an object are also known as attributes, which explained why the error is named AttributeError. In different words, if you are using an object and the access to the attribute(field or method) fails, you will get this error. Let’s see some examples:
person_dict = {'age':13,'name': 'Larry'} person_dict.push()
Ouput:
Traceback (most recent call last): File line 2, in <module> person_dict.push() AttributeError: 'dict' object has no attribute 'push'
The code above failed since python dictionaries don’t have a push
method.
Your code will raise an indexerror exception when it attempts to access an index that doesn’t exist. For instance, if you have a list containing three items and you try to access item #6.
list = ['monday','tuesday','wednesday','thursday'] print(list[6])
Output:
Traceback (most recent call last): File line 2, in <module> print(list[6]) IndexError: list index out of range
It is common to encounter this error when a loop is going over a collection, but the loop is looping beyond the last collection’s item. See the example below:
list = ['monday','tuesday','wednesday','thursday'] for i in range(0,len(list)+1): print(list[i])
Output:
monday tuesday Traceback (most recent call last): wednesday thursday File "/Users/martarey/dev_python/python_projects/errors/errors.py", line 3, in <module> print(list[i]) IndexError: list index out of range
The code will fail when attempting to access index #4, which will be the list’s 5th item. Since there is no 5th item, the code returns an IndexError.
To summarise, this article covered some of the most common errors, like the python nameerror name is not defined and others, that you might encounter when running your code. Understanding these errors and what they mean will help you anticipate these problems when coding, resulting in a more stable and reliable code.
Hope you enjoy the article and thank you so much for reading and supporting this blog! 🙂
Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications
Unique lay-out and teaching programming style helping new concepts stick in your memory
Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples
Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.
Excellent read for anyone who already know how to program and want to learn Best Practices
Perfect book for anyone transitioning into the mid/mid-senior developer level
Great book and probably the best way to practice for interview. Some really good information on how to perform an interview. Code Example in Java