Errors are inevitable when you are programming. As you write code, errors will start raising. The better you understand these errors, the easier it will be to avoid them. In this article you 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.
he goal of an error, or exception, is flagging something unexpected happened while running the code. Some of these situation 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.
This error occurs when the code you write doesn’t follow the python syntax rule. For example, not closing a parenthesis will lead to a syntax error. The python parser won’t be able to parse the code if it doesn’t follow the syntax rule, therefore it can’t process it any further. Let’s see some examples:
list = [1, 23, 45, 0, 9] for item in list print(item)
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.
list = [1, 23, 45, 0, 9] for item in list: print(item
File line 4 ^ SyntaxError: unexpected EOF while parsing
The code above raised an error because line 3 is missing the closing parenthesis.
You will encounter a nameerror ( 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 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:
number = 1 print(num)
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.
def print_age(age): print('My age is: '+str(age)) print__age(14)
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 when I called the function I used double underscore __. That’s why the code can’t find the function
I hope you enjoyed the article and thanks for reading! Happy Coding! 😃