Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python
1. Python Error – Objective
In this Python Error tutorial, we will discuss what a syntax error in Python is. Along with this, we will study Python exceptions, error messages, and come in-built exception in the Python Programming Language.
It will cover all possible Python errors and Python exceptions to help you run your Python code smoothly, as there are many reasons why to learn Python.
So, let’s begin with Python Error and Python Exception.
2. Syntax Errors in Python
In your code, when you mess up the rules of Python Syntax, your code doesn’t run.
Common causes of syntax errors:
- Missing colons: After every flow statement, like if, while, for loops, colons (:) are used to define the indented block, like in functions, loops and in conditionals.
- Wrong indentation: Python uses indentation to define the structure of the code blocks.
- Syntax errors can occur due to the wrong use of keywords or because of keywords being misspelt.
The following code causes a syntax error.
>>> if 2>1 print("2")
SyntaxError: invalid syntax
This code doesn’t run because it misses a colon after the condition 2>1.
A syntax error, also called a parsing error, displays ‘Syntax Error: invalid syntax’.
3. What is a Python Exception?
It may be convenient to recognise the problems in your Python code before you put it to real use. But that does not always happen. Sometimes, problems show up when you run the code; sometimes, midway through that.
A Python exception is an error that’s detected during execution. It may be fatal for the program, but not necessarily so. Let’s take the most common example.
>>> a,b=1,0 >>> print(a/b)
Traceback (most recent call last):
File “<pyshell#208>”, line 1, in <module>
print(a/b)
ZeroDivisionError: division by zero
Throughout our Python tutorials so far, you’ve noticed words like TypeError, NameError, and so on. It’s time to find out what that is. Also, learn Exception Handling in Python for Python Programming.
4. Python Error and Python Exception Message
When Python errors and exceptions occur, it prints a four-line message on the screen if not handled.
The first line declares that this is a traceback. This means that the interpreter traces the Python exception back to its source.
The second tells us the line number for the code that caused the Python exception. In our case, it is line 1. #208 means this is the 208th statement we’re running in the interpreter since we opened it.
The third line tells us which line (the statement that) caused the Python exception.
Finally, the fourth line tells us the type of Python exception that occurred. This is accompanied by a short description of what happened.
5. In-built Python Exception
Now that we know what an exception is, we will talk about a list of Python exceptions that are built into Python. As you read the list, try to recall if you ever encountered any of these Python exceptions. Tell us in the comments.
1. AssertionError in Python
This Python exception raises when an assert statement fails. This is also called a Python raise expression.
A successful assert statement looks like this:
>>> assert(1==1)
But when we write the following code, we get an AssertionError:
>>> assert(1==2)
Traceback (most recent call last):
File “<pyshell#213>”, line 1, in <module>
assert(1==2)
AssertionError
We’ll take the assert statement in detail in a future lesson.
2. AttributeError in Python
This one occurs when an attribute assignment or reference fails. As an example, let’s take a class
‘fruit’.
>>> class fruit:
pass
>>> fruit.size
Traceback (most recent call last):
File “<pyshell#223>”, line 1, in <module>
fruit.size
AttributeError: type object ‘fruit’ has no attribute ‘size’
Here, the attribute size does not exist. Hence, it raises an AttributeError.
3. EOFError in Python
This Python exception raises when the input() function reaches the end-of-file condition.
4. FloatingPointError in Python
When a floating-point operation fails, this Python error occurs.
5. GeneratorExit in Python
This raises when a generator’s close() method is called.
6. ImportError in Python
When the imported module isn’t found, an ImportError occurs.
>>> from math import ppi
Traceback (most recent call last):
File “<pyshell#234>”, line 1, in <module>
from math import ppi
ImportError: cannot import name ‘ppi’
7. IndexError in Python
When you access an index on a sequence that is out of range, you get an IndexError.
>>> list=[1,2,3] >>> list[3]
Traceback (most recent call last):
File “<pyshell#236>”, line 1, in <module>
list[3]
IndexError: list index out of range
8. KeyError in Python
This raises when a key isn’t found in a dictionary.
>>> dict1={1:1,2:2}
>>> dict1[3]
Traceback (most recent call last):
File “<pyshell#239>”, line 1, in <module>
dict1[3]
KeyError: 3
9. KeyboardInterrupt in Python
This one occurs when the user hits the interrupt key (Ctrl + C).
>>> while True: print("Hello")
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Traceback (most recent call last):
File “<pyshell#244>”, line 1, in <module>
while True: print(“Hello”)
KeyboardInterrupt
10. MemoryError in Python
This raises when an operation runs out of memory.
11. ModuleNotFoundError in Python
When you import a module that does not exist, you will get the ModuleNotFoundError.
>>> import maths
Traceback (most recent call last):
File “<pyshell#233>”, line 1, in <module>
import maths
ModuleNotFoundError: No module named ‘maths’
12. NameError in Python
A NameError occurs when a name isn’t found in a scope.
>>> eggs
Traceback (most recent call last):
File “<pyshell#245>”, line 1, in <module>
eggs
NameError: name ‘eggs’ is not defined
13. NotImplementedError in Python
An abstract method raises a NotImplementedError.
14. OSError in Python
Now this one is raised when a system operation causes a system-related error.
15. OverflowError in Python
This raises when the result of an arithmetic operation is too large to be represented.
16. ReferenceError in Python
This is raised when a weak reference proxy is used to access a garbage-collected referent.
17. RuntimeError in Python
When an error does not fall under any specific category, we call it a RuntimeError.
18. StopIteration in Python
The next() function raises StopIteration to indicate that no further items are to be returned by the iterator.
>>> def countdown():
n=4
while(n>0):
yield n
n-=1
>>> c=countdown()
>>> next(c)
4
>>> next(c)
3
>>> next(c)
2
>>> next(c)
1
>>> next(c)
Traceback (most recent call last):
File “<pyshell#23>”, line 1, in <module>
next(c)
StopIteration
19. IndentationError in Python
An IndentationError raises on incorrect indentation.
20. TabError in Python
When the indentation is inconsistent in tabs and spaces, there’s a TabError.
21. SystemError in Python
When the interpreter detects an internal error, it’s a SystemError.
22. SystemExit in Python
The sys.exit() function raises this one.
23. TypeError in Python
When you apply a function or an operation to an object of the incorrect type, you get a TypeError.
>>> '10'+10
Traceback (most recent call last):
File “<pyshell#38>”, line 1, in <module>
’10’+10
TypeError: must be str, not int
24. UnboundLocalError in Python
You get an UnboundLocalError when you try to access a local variable without first assigning a value to it.
>>> def sayhi():
m+=1
print(m)
>>> sayhi()
Traceback (most recent call last):
File “<pyshell#53>”, line 1, in <module>
sayhi()
File “<pyshell#52>”, line 2, in sayhi
m+=1
UnboundLocalError: local variable ‘m’ referenced before assignment
25. UnicodeError in Python
When a Unicode-related encoding/decoding error occurs, you get the UnicodeError exception.
26. UnicodeEncodeError in Python
This is a Unicode error during encoding.
Learn: Python Inheritance, Method Overloading & Method Overriding
27. UnicodeDecodeError in Python
The Unicode error during decoding is termed UnicodeDecodeError.
28. UnicodeTranslateError in Python
A UnicodeTranslateError occurs during translation.
29. ValueError in Python
You get a ValueError when you send in an argument of the correct type, but an improper value.
>>> int(input())
3.5
Traceback (most recent call last):
File “<pyshell#55>”, line 1, in <module>
int(input())
ValueError: invalid literal for int() with base 10: ‘3.5’
30. ZeroDivisionError in Python
Finally, a ZeroDivisionError is one we’ve seen in section 3. When the denominator of a division is 0, this Python exception is raised. This doesn’t necessarily violate syntax.
>>> print(1/0)
Traceback (most recent call last):
File “<pyshell#56>”, line 1, in <module>
print(1/0)
ZeroDivisionError: division by zero
So, this is all about the Python Error and Python Exception. Hope you like our explanation.
6. Conclusion
In this module, we learned about Python errors and Python exceptions and looked at some built-in exceptions in Python. These are unexpected situations at runtime. Furthermore, if you have any queries, feel free to ask in the comment box.
