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
In Python, indentation refers to the use of spaces or tabs at the beginning of a line to define the structure of the code. It’s essential for separating code blocks, making the code readable and ensuring it works correctly.
The problem arises when indentation isn’t done properly, leading to an "IndentationError" in Python.
Understanding what is indentation in Python with example can help you avoid these errors and improve your code organization. Once you grasp this, you’ll write cleaner, error-free Python code.
In this guide, you’ll learn the importance of indentation, common pitfalls, and how to fix the dreaded indentation error in Python. Read on!
“Enhance your Python skills further with our Data Science and Machine Learning courses from top universities — take the next step in your learning journey!”
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
“Start your coding journey with our complimentary Python courses designed just for you — dive into Python programming fundamentals, explore key Python libraries, and engage with practical case studies!”
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")
3. Using an IDE or Text Editor with Python Support
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.
A. 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")
A. 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.
A. 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.
A. 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.
A. 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.
A. 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.
A. 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.
A. 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.
A. Yes, many text editors and IDEs can automatically correct indentation errors in Python by converting tabs to spaces or aligning blocks of code.
A. Yes, most modern IDEs such as PyCharm or VSCode display indentation guides that help you visualize indentation levels, preventing indentation errors in Python.
A. 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
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
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.