[Solved] IndentationError: unexpected unindent
Introduction:
- An
IndentationError: unexpected indentoccurs when Python encounters an unexpected level of indentation in your code. This typically happens when there is an extra space or tab before a line where extra indentation is not expected.
Example of IndentationError:
Consider the following program where the body of the
addition()function is not properly indented:pythondef addition(a, b): result = a + b return result print(addition(10, 20))
Output:
File "answer.py", line 3
return result
^
IndentationError: unexpected indent
- Python indicates that it encountered an unexpected indent at line 3.
Solution:
To fix this error, ensure the statements within the function are consistently indented. Here is the corrected program:
pythondef addition(a, b): result = a + b return result print(addition(10, 20))
Output: 30
The program runs without any IndentationError.
Summary:
- In this tutorial, we learned how to solve the
IndentationErrorthat occurs when there is an unexpected indentation level in the code. Proper indentation is crucial in Python to define code blocks and ensure the program runs correctly. Practice writing and indenting functions to avoidIndentationError: unexpected indentin your Python programs!