Why does Unexpected Indent Error occur?
Below, are the reasons for occuring Unexpected Indent Errors in Python.
- unexpected indent
- expected indented block
- unindent does not match
Unexpected Indent
In this example, the below code has an Unexpected Indent Error because the `print` statement lacks proper indentation under the `my_function` definition.
Python3
def my_function(): print ( "Hello, World!" ) |
Hangup (SIGHUP)
File "Solution.py", line 2
print("Hello, World!")
^
IndentationError: expected an indented block
expected indented block
In this example, below code has an Unexpected Indent Error. To resolve it, ensure that both `print` statements inside the `if-else` block are indented consistently, typically with four spaces or a tab.
Python3
if x > 0 : print ( "Positive number" ) else : print ( "Non-positive number" ) |
Hangup (SIGHUP)
File "Solution.py", line 2
print("Positive number")
^
IndentationError: expected an indented block
unindent does not match
In this example below, code has an Unexpected Indent Error because the second `print` statement is indented at a different level compared to the first one inside the `my_function`.
Python3
def my_function(): print ( "Indented correctly" ) print ( "Indented incorrectly" ) |
Hangup (SIGHUP)
File "Solution.py", line 3
print("Indented incorrectly")
^
IndentationError: unindent does not match any outer indentation level
How To Resolve The Unexpected Indent Error In Python
In Python, indentation is crucial for defining blocks of code, such as loops, conditionals, and functions. The Unexpected Indent Error occurs when there is an indentation-related issue in your code that Python cannot interpret correctly. This error typically happens when the indentation is inconsistent or there is a mix of tabs and spaces.
What is Unexpected Indent Error?
The Unexpected Indent Error is a common syntax error in Python that occurs when the interpreter encounters an indentation that it does not expect. Python relies on consistent indentation to define the structure of the code, and any unexpected changes can lead to this error.
Syntax :
IndentationError: expected an indented block
Contact Us