Subscribe to our Youtube Channel To Learn Free Python Course and More
When you write any program, it’s hard to write an error-free program. Whenever you make mistakes while writing the program, Python interpreter throws an error message. In this section, we will see the common errors that occur while writing a program.
Syntax Errors
Every programming language has its own syntax. The syntax is particular of writing the code. So if you make any mistake in syntax, the python interpreter throws a syntax error with an error message. See the below code:
# Syntax error
list = [1, 2, 3, 4, 5]
for elm in list
print(elm)
'''
for elm in list
File "<stdin>", line 1
for elm in list
^
SyntaxError: invalid syntax
'''
Here you can see that in for loop colon(:) sign is missing that’s why Python throws this error. So whenever you encounter syntax error, look at your code syntax.
Exceptions
Even if your syntax is correct, Python throws an error after running the program. These types of error called runtime errors or exceptions. Let’s see some common exception.
TypeError
TypeError is raised when a function is applied to incorrect object. See the below example.
def add2(n):
return n + 2
add2('hello')
'''
Output: TypeError: must be str, not int
'''
IndexError
IndexError is raised when the index of any sequence datatype(String, LIst, tuple) is out of range. See the below example.
a = [1, 2, 3, 4, 5]
print(l[5])
'''
Output:
IndexError: list index out of range
'''
NameError
NameError is raised when a variable is not found in the local or global scope. See the below example.
tax_cut = 50
def bill(amount):
pay = amount+taxcut
return pay
bill(100)
'''
Output:
NameError: name 'taxcut' is not defined
The error occurs because taxcut is not in a global or local scope.
'''
KeyError
The keyError is raised when the key is not found in the dictionary. See the below example.
d = {1: 'a', 2: 'b'}
print(d[3])
'''
Output:
KeyError: 3
'''
IndentationError
IndentationError is raised when there is incorrect indentation. See the below example.
l = [1, 2, 3, 4, 5]
for elm in l:
print(elm)
'''
Output:
IndentationError: expected an indented block
'''
ZeroDivisionError
ZeroDivisionError is raised when the second operand of division or modulo operation is zero. See the below example.
print(1/0)
# Output: ZeroDivisionError: division by zero
print(1%0)
# Output: ZeroDivisionError: division by zero
Top comments (0)