Indentation is an important feature of readable, maintainable code, but few languages ​​enforce it. Python is one of those few.

If Python determines that your code is indented incorrectly, you will see an “indentation error” message when running your code. But how do you fix it, and how do you prevent it in the future?

Why do you get an indentation error in Python?

The “Indentation error: indented block expected” error is something you might see when you first start using Python, especially if you’ve come from another programming language.

The specifics of Python’s indentation rules are complicated, but they boil down to one thing: indent code in blocks. The same goes for functions, if clauses, and so on. Here is an example of incorrectly formatted Python code.

If you indent with spaces, you can really use any number you like, as long as you’re consistent and clear. Most programmers use two, four or eight spaces.

Common cases of correct indentation

Here are some examples you can refer to, so you can make sure you’re indenting correctly.

Make sure your editor indents correctly

Most modern text editors support automatic code indentation. If your editor determines that a line of code should be indented, it will automatically add tabs or spaces.

However, no editor can make automatic indentation bulletproof. You still have to pay attention to the indenting as some cases are ambiguous.

In this example, the last return statement is indented one level from the function signature on the first line. However, if you place your cursor at the end of the last line and press Enter, one of two things can happen.

Your editor cannot distinguish between these two cases: you may or may not want to add more code to the if/else block.

Handling Python’s ‘Expected an indented block’ error

Like any other programming language, errors in Python are a daily occurrence. Python’s strict rules about indentation may add a new kind of error to thinking, but they are useful. Properly indented code is more readable and consistent across teams.

Indentation error isn’t the only one you’ll have to deal with. It helps to become familiar with common Python errors so that you know how to debug them and what to do to fix them.

Leave a Reply

Your email address will not be published. Required fields are marked *