When writing Python programs, you may encounter different types of errors. Understanding these errors makes debugging much easier.
we'll learn about five common Python errors:
- SyntaxError
- NameError
- TypeError
- IndentationError
- TabError
1. SyntaxError
What is a SyntaxError?
A SyntaxError occurs when you break Python's grammar rules. Python cannot understand the code because it is written incorrectly.
Example
if 10 > 5
print("Hello")
Output
SyntaxError: expected ':'
Why?
The colon (:) is missing after the if statement.
Correct Code
if 10 > 5:
print("Hello")
2. NameError
What is a NameError?
A NameError occurs when you use a variable or function that has not been defined.
Example
print(age)
Output
NameError: name 'age' is not defined
Why?
The variable age was never created.
Correct Code
age = 25
print(age)
3. TypeError
What is a TypeError?
A TypeError occurs when an operation is performed on incompatible data types.
Example
age = 20
name = "Vinoth"
print(age + name)
Output
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Why?
Python cannot add an integer (int) and a string (str).
Correct Code
print(str(age) + name)
4. IndentationError
What is an IndentationError?
An IndentationError occurs when Python expects an indented block, but the indentation is missing or incorrect.
Example
def greet():
print("Hello")
Output
IndentationError: expected an indented block
Why?
The print() statement should be inside the function and must be indented.
Correct Code
def greet():
print("Hello")
5. TabError
What is a TabError?
A TabError occurs when you mix Tabs and Spaces for indentation in the same block of code.
Example
def buy_grocery():
print("Buying Grocery Items")
return "Grocery Bag"
Output
TabError: inconsistent use of tabs and spaces in indentation
Why?
- The
print()statement is indented using a Tab. - The
returnstatement is indented using Spaces.
Python cannot determine whether both lines belong to the same block.
Correct Code
def buy_grocery():
print("Buying Grocery Items")
return "Grocery Bag"
Tip: Use 4 spaces for indentation throughout your Python program. Avoid mixing tabs and spaces.
Summary Table
| Error | Cause | Example |
|---|---|---|
| SyntaxError | Invalid Python syntax | Missing : after if
|
| NameError | Variable or function not defined | print(age) |
| TypeError | Using incompatible data types | 10 + "20" |
| IndentationError | Missing or incorrect indentation | Function body not indented |
| TabError | Mixing tabs and spaces | One line uses a tab, another uses spaces |
Remember these common Python errors:
- SyntaxError – Invalid syntax.
- NameError – Undefined variable or function.
- TypeError – Wrong data types.
- IndentationError – Incorrect indentation.
- TabError – Mixed tabs and spaces.
Top comments (0)