Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected Indentation in Visual Studio Code with Python

the following code

accounts = f.get_sepa_accounts()

for account in accounts:
    print(account)

is throwing the following error:

>>>     print(account)
  File "<stdin>", line 1
    print(account)
    ^
IndentationError: unexpected indent

I just moved to Visual Studio Code, so no idea if this is a problem specific to the application. I tried 4 spaces and a tab already..Doesn't do anything.

like image 677
rStorms Avatar asked Sep 07 '18 14:09

rStorms


People also ask

How do you fix an unexpected indent in Python?

Just say "no" to tabs. Most editors allow them to be automatically replaced by spaces. The best way to avoid these issues is to always use a consistent number of spaces when you indent a subblock, and ideally use a good IDE that solves the problem for you. This will also make your code more readable.

Why does Python keep saying unexpected indent?

Python does not have this feature, so the language depends heavily on indentation. The cause of the “IndentationError: unexpected indent” error is indenting your code too far, or using too many tabs and spaces to indent a line of code.


2 Answers

Update:- The more recent versions of VSCode don't seem to have this issue.

You have probably used tabs when indenting. You can check this by selecting the code. When selected the tabs are highlighted with a right pointing arrow in VS Code as shown in the image below:-

Screenshot showing arrows for tabs and dots for spaces

Notice the two arrows in the second line. See how the second line is error because of this. You fix this by selecting the two tabs and pressing Ctrl+H. Replace with the right amount of spaces.

In short replace tabs with spaces.

like image 186
ambassallo Avatar answered Oct 18 '22 00:10

ambassallo


Press F1 and start typing 'Indentation to spaces' and you will be able to find 'Convert Indentation to Spaces' option, select and click enter.

Next time, mostly you just have to press F1 and enter because it is selected by default since you used it recently.

F1 and enter

like image 3
Senthil Vikram Vodapalli Avatar answered Oct 17 '22 23:10

Senthil Vikram Vodapalli