“unexpected indent” errors in Python
If you’ve used Python, you know that whitespace is used to delimit blocks of code.
But whitespace comes in two different flavors: tabs and spaces, and you have to pay attention to which one you are using:
When you press the TAB key on your keyboard, a code is sent to the computer corresponding to the “\t” character, which is different from the ” ” (space) character.
Many text editors, by default, insert a “\t” character when you press the TAB key. But this may cause some problems in a Python script.
Say you copy a program from a site and paste it into your text editor. The site you copied it from (like this one) uses spaces. Then in your text editor you add your own lines of code here and there . . . but your text editor inserts a “\t” character. Looking at the screen it doesn’t look any different. However, when you run your program you may get an “unexpected indent” error, and that’s because both tabs and spaces are being used in the script.
Most text editors that support syntax highlighting of code also allow you to change the behavior of the TAB key. For Python, the convention is to use 4 spaces, so you can set your text editor to insert 4 spaces every time you hit the TAB key.
But what about fixing your existing code? Doing a find-replace can be a little tricky. One thing you can do is open a text file that you KNOW has an actual tab character in it. You can tell because when you select some whitespace, chunks of space are selected at a time. Those are the tab characters. Copy one and paste it into the find section of the find-replace dialog box of your text editor, then in the replace box put four spaces, and replace all.
You can find more information on spaces in Python here
Here are a couple more ways to convert tabs to spaces.
Tags: indent, text editor, whitespace