[Solved] IndentationError
Introduction:
- An
IndentationError: expected an indented block after 'for' statementoccurs when Python expects an indented block of code following a for statement, but it is missing or improperly indented. This guide will help you understand and fix this common error.
Example of IndentationError:
Consider this program where the print statement inside the for loop is not properly indented:
pythonfor i in range(10): print(i)
Output:
File "example.py", line 2
print(i)
^
IndentationError: expected an indented block after 'for' statement on line 1
- Python clearly indicates that it expected an indented block after the for statement on line 1.
Solution:
To fix this error, ensure the statements within the for loop are properly indented. Here is the corrected program:
pythonfor i in range(10): print(i)
Output:
0
1
2
3
4
5
6
7
8
9
- The program runs without any
IndentationError.
Summary:
- In this tutorial, we learned how to solve the
IndentationErrorthat occurs when the block inside a for statement is not properly indented. Proper indentation is crucial in Python to define code blocks and ensure the program runs correctly. Practice writing and indenting for loops to avoidIndentationError: expected an indented block after 'for' statementin your Python programs!