Using the Wrong Indentation
Using the Wrong Indentation. There are two sub-classes of
SyntaxError that deal with indentation issues specifically. The first that you’ll see is
IndentationError. While other programming languages use curly braces to denote blocks of code, Python uses whitespace.
That means that Python expects the whitespace in your code to behave predictably. It will raise an
IndentationError if there’s a line in a code block that has the wrong number of spaces. While this may not be immediately apparent, line 5 is only indented by three spaces.
It should be in line with the
for loop statement, which is four spaces across. Thankfully, Python can spot this easily and will quickly tell you what the issue is. There’s also a bit of ambiguity here, though.
Even though the traceback looks a lot like the
SyntaxError traceback, it’s actually an
IndentationError. The error message is very helpful and it tells you that the indentation level of the line doesn’t match any other indentation level. In other words,
print('done') is indented by three spaces, but Python can’t find any other line of code that matches this level of indentation.
You can fix this quickly by making sure the code lines up with the expected indentation level. Here, this line can easily be corrected by adding a single space, bringing it into line with the
for statement, and making sure that this happens after the
for loop has completed.
The second indentation-related error is the
TabError, which you’re going to see whenever there is a line that contains either tabs or spaces for its indentation, while the rest of the file contains the other.
01:56 Here, you can see some code, which looks perfectly okay. While the indentation is quite large, it’s the same for all of the lines inside the function, and this looks like it should work. However, one of the lines is indented with a tab, and the others are indented using spaces. This will only become apparent when you either inspect the code closely, or you ask Python to run it, as you’re going to see next.
02:35 This is one area where most modern code editors which understand Python syntax won’t let you make this kind of mistake. I’ve actually had to do this in a different editor to allow this to occur.
03:00 In this particular case, tabs have been set to eight spaces, so they look identical. However, this is easily fixed, in this case, by highlighting the unwanted tab and then using the Tab key in the editor.
Become a Member to join the conversation.