For working professionals
For fresh graduates
More
13. Print In Python
15. Python for Loop
19. Break in Python
23. Float in Python
25. List in Python
27. Tuples in Python
29. Set in Python
53. Python Modules
57. Python Packages
59. Class in Python
61. Object in Python
73. JSON Python
79. Python Threading
84. Map in Python
85. Filter in Python
86. Eval in Python
96. Sort in Python
101. Datetime Python
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
107. Append in Python
110. Assert in Python
113. Bool in Python
115. chr in Python
118. Count in python
119. Counter in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
125. Format in Python
131. Index in Python
132. Interface in Python
134. Isalpha in Python
136. Iterator in Python
137. Join in Python
140. Literals in Python
141. Matplotlib
144. Modulus in Python
147. OpenCV Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
156. Python Arrays
158. Python Frameworks
160. Python IDE
164. Python PIP
165. Python Seaborn
166. Python Slicing
168. Queue in Python
169. Replace in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
179. Split in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
195. What is Pygame
197. XOR in Python
198. Yield in Python
199. Zip in Python
Why does Python throw an error just because you missed a space or tab?
Because in Python, indentation isn't just about formatting—it's part of the syntax.
Indentation in Python defines how your code blocks are structured. Unlike many other languages that use braces {} to group code, Python uses whitespace. That means even a single missing tab can cause your entire program to crash.
In this blog, you’ll learn the rules of indentation in Python, how it affects loops, conditionals, functions, and classes. We’ll also walk you through common indentation errors like IndentationError and TabError, and show you how to fix them quickly.
By the end, you’ll know how to write clean, readable, and bug-free Python code with the correct indentation. Want to put your clean coding skills to work? Our Data Science Courses and Machine Learning Courses teach Python in real project environments where structure really matters.
In Python, indentation determines the grouping of statements, a unique feature compared to many other programming languages that use curly braces for this purpose.
The rules for indentation are simple but strict:
Here’s an example to better understand how to apply indentation properly:
def greet(name): # Define a function
if name: # Check if name is not empty
print(f"Hello, {name}") # Indented because it's part of the if block
else:
print("Hello, Stranger") # Indented because it's part of the else block
greet("Ajay")
Output:
Hello, Ajay
Explanation
If you're exploring Python through basic exercises and want to see how it's used in real-world data science problems, consider learning more through a structured program in Data Science and Machine Learning.
Indentation errors in Python typically occur when the program is unable to correctly determine the structure of the code due to inconsistent or incorrect indentation.
Unlike other languages that use curly braces {} to define blocks of code, Python uses indentation to group statements, which makes it more prone to indentation errors.
Common causes of indentation errors include:
Here’s an example of how an IndentationError in Python can occur:
def greet(name): # Define the function
if name: # Incorrect indentation of the if statement
print(f"Hello, {name}") # Indented correctly inside the if block
else:
print("Hello, Stranger")
Output:
IndentationError: expected an indented block
Explanation:
By understanding how and why indentation errors in Python occur, you can prevent these issues and ensure your Python code runs smoothly.
Fixing indentation errors in Python is straightforward once you understand the cause.
The first step in fixing indentation errors is ensuring consistency. Python allows either spaces or tabs for indentation, but you should stick to one throughout your code. The Python PEP 8 style guide recommends using 4 spaces per indentation level.
Example:
# Correct indentation using spaces
def greet(name):
if name:
print(f"Hello, {name}")
else:
print("Hello, Stranger")
If you accidentally use a tab in one part and spaces in another, Python will raise an indentation error.
Fix: Ensure you are using either spaces or tabs consistently. In most editors, you can configure it to replace tabs with spaces automatically.
For nested structures like loops, conditionals, and function definitions, indentation levels need to be consistent. A common mistake is using incorrect indentation for these nested blocks.
Example:
def greet(name):
if name:
print(f"Hello, {name}")
else: # This else has incorrect indentation
print("Hello, Stranger")
Output:
IndentationError: unexpected indent
Fix: Ensure that all nested blocks inside functions, loops, and conditionals follow the correct level of indentation:
def greet(name):
if name:
print(f"Hello, {name}")
else:
print("Hello, Stranger")
Many IDEs and text editors (like PyCharm, VSCode, or Sublime Text) highlight indentation errors and allow you to correct them easily. These editors often include features like:
By using an appropriate IDE, you can spot and fix indentation errors quickly, making the process smoother.
One of the most common causes of indentation errors is mixing tabs and spaces. Python is very particular about this, and using a mix will result in an error.
Example:
def greet(name):
if name: # Using a tab here
print(f"Hello, {name}")
else: # Using spaces here
print("Hello, Stranger")
Output:
TabError: inconsistent use of tabs and spaces in indentation
Fix: Use either spaces or tabs but not both. The recommended way is to use spaces, and you can configure your editor to convert tabs to spaces automatically.
Once you understand how indentation works in Python, fixing indentation errors becomes much easier. The key is consistency. Always use spaces (preferably 4) and make sure that every nested block is properly aligned with the parent block.
1. What is indentation in Python?
a) Placing semicolons at line ends
b) Adding parentheses to expressions
c) Whitespace used to define code blocks
d) Importing external libraries
2. Why is indentation important in Python?
a) For styling only
b) To reduce memory usage
c) To indicate the structure and flow of the program
d) To handle exceptions
3. What is the default number of spaces for one indentation level in Python style guides (PEP 8)?
a) 2
b) 4
c) 6
d) 8
4. What happens if indentation is inconsistent in a Python block?
a) Code runs with a warning
b) Code ignores spacing
c) IndentationError is raised
d) Only the first line runs
5. Which of the following blocks will cause an indentation error?
a) if True:
print("Hi")
print("Hello")
b) for i in range(3):
print(i)
print("Done")
c) def func():
pass
d)while True:
break
6. Which editor setting can help avoid indentation errors?
a) Enable auto-save
b) Use monospaced fonts
c) Convert tabs to spaces
d) Turn off syntax highlighting
7. What is a common cause of IndentationError: unexpected indent?
a) Using double quotes
b) Starting a new block with a tab instead of spaces
c) Using too many comments
d) Importing wrong modules
8. What does IndentationError: unindent does not match any outer indentation level mean?
a) You're missing a loop
b) The line is too long
c) You're trying to reduce indentation incorrectly
d) There's a print error
9. A student writes a function, but one line inside is indented with 2 spaces and others with 4. What will happen?
a) Function runs
b) Only indented lines run
c) Raises IndentationError
d) Python adjusts spacing automatically
10. You copy code from the web. It throws an indentation error. What's the best fix?
a) Delete all indentation
b) Manually align code using consistent spaces or tabs
c) Change all spaces to tabs
d) Comment out the first line
11. Your company enforces 4-space indentation in all code. What is the best way to maintain this across the team?
a) Send reminders
b) Use print statements
c) Use code linters or auto-formatting tools like black or flake8
d) Avoid indentation completely
Indentation in Python with example refers to the spaces or tabs used to define the block of code under a statement like if, for, or a function. Python uses indentation to determine the scope of code blocks, unlike other languages that use curly braces {}.
Example:
if True:
print("This is indented properly")
Indentation error in Python occurs when there is inconsistent or incorrect spacing in the code. This might happen when spaces and tabs are mixed, or when code blocks are not aligned properly. Python requires uniform indentation.
While both spaces and tabs can be used for indentation in Python, spaces are the preferred method. Mixing spaces and tabs in the same file will lead to indentation error in Python.
To avoid indentation errors in Python, use a consistent indentation style. Set your editor to insert spaces (typically 4) instead of tabs. Avoid mixing spaces and tabs within the same code block.
Fix indentation errors in Python by ensuring all code blocks are aligned properly using spaces or tabs. Most modern text editors show where the indentation errors occur, making it easier to spot and fix them.
Python uses indentation as a key element for defining code blocks. This makes the code more readable and easier to maintain, but it also means indentation error in Python can be a common source of bugs.
No, mixing spaces and tabs for indentation causes indentation errors in Python. It is recommended to use only spaces or only tabs throughout your code.
The IndentationError in Python appears when the code indentation is inconsistent. For example, Python will raise an error like IndentationError: unexpected indent when you improperly indent a block of code.
Yes, many text editors and IDEs can automatically correct indentation errors in Python by converting tabs to spaces or aligning blocks of code.
Yes, most modern IDEs such as PyCharm or VSCode display indentation guides that help you visualize indentation levels, preventing indentation errors in Python.
If you encounter an IndentationError, check your code for inconsistent use of spaces or tabs. Align your code properly and re-run the script.
Take our Free Quiz on Python
Answer quick questions and assess your Python knowledge
Author|900 articles published
Previous
Next
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.