IndentationError: Unexpected Unindent in Python
Python indentation is a part of the syntax. It’s not just for decoration. You’ll learn what these errors mean and how to solve them: IndentationError: unexpected indent IndentationError: expected an indented block IndentationError: unindent does not match any outer indentation level IndentationError: unexpected unindent So if you want to learn how to solve those errors, then you’re in the right place. Let’s kick things off with error #1! How to Solve IndentationError: unexpected indent in Python Python is a beautiful language. One of the key features of this beauty is the lack of curly braces and other symbols that mark the beginning and end of each block. Even in C it is considered a good practice to indent, denoting different levels in the code. Compare the same C ++ code with and without indentation. First with the indentation: And the same code without indentation: Both codes will compile and run, but the indented code is a lot easier to read. In the second case, it isn’t clear which parenthesis goes with which. In Python, parentheses aren’t needed, but indentation is. This is what the C++ program would look like in Python: However, there is a downside to this beauty. If you make a mistake in the indentation, the program will be inconsistent, which will lead to errors when it’s running. Perhaps, this is a better option than changing the indentation and not getting the error, but changing the meaning of the program. The error IndentationError: unexpected indent is one that results from wrong indentation. It happens when there are no keywords in front of the indentation. Here’s an example: Python expects a keyword line to come before an indented line. List of keywords followed by an indented line: class: class definition def: function definition for: a loop with a parameter while: a loop with a condition if, elif, else: conditional operator try, except, finally: exception handling with: a context operator