The Mysterious "Unexpected Indent" Error (Hidden Tab Characters)


For anyone having this issue even though their code is actually correct…

In this Python training, it uses 2 spaces for indentation, but somehow there can be a mishap where your indentation is messed up and continues to break your code even though it looks perfectly alright and indentations match up perfectly. To fix this, I removed all my indentations and used the space key to indent my code and then all was OK.

Here are pictures of the code. The first one is from another site that is an online Python tool I use for testing. Notice how the indentation looks correct. But, it gives an error as well about indentation.

Here’s what the actual code looks like in Notepad++ when you turn on invisible characters. Notice the arrows at the end of the code. Those are tabs when they should be spaces. Both Codecademy and this other site didn’t automatically fix this for me.

Auto Indenting Never Works

You have essentially discovered the approach to take when indentation is an issue… Remove all indents and re-insert them as space characters, as apply to each block level.


Shouldn’t pressing TAB for indentation automatically convert to spaces though when working in this Python training? Sort of like an enhanced auto-indentation handling mechanism.


I have never seen an editor that does that. Auto-indent uses TAB, unfortunately, which often results in mixed tabs and spaces.


There are modern editors that convert tabs to spaces.


The best tool is the one between our shoulders. Good habits more than replace any fancy features in an editor. We could wish that the IDE for the Python lessons had such a feature, but like they say, if wishes were horses, beggars would ride.


Good habits are fine and all. But, when I do it enough, it’s just one of those things I don’t want to think about. More about focusing on the concept of the code than making sure to get those 2 spaces in front. It’s like a productivity enhancement. 1 key press (tab) versus 2 key presses (spaces) where needed.


As mentioned earlier, given this is just the beginning there is no impetus to concern ourselves with productivity or efficiency. This is a learning environment, not production. The only real way to master Python is to get a handle on block syntax so it no longer presents a problem.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.