pythonvisual-studioindentation

Why do I get errors using shift-enter to run Python code in my IDE?


I am trying to use Python (2.17.15 via Anaconda) on Visual Stodio Code on my Mac. I have the following simple code:

def function(x):
    y = x + 2
    return y
        

This code is giving me an indentation error:

   return y
    ^
IndentationError: unexpected indent
>>>     return y
  File "<stdin>", line 1
    return y
    ^
IndentationError: unexpected indent
>>>

Needless to say that Jupyter or Spyder have no problem with this. I checked that on VSC tab gives 4 spaces. All similar questions are related to this, but I cannot fix it.

Other, built in functions of Python work fine.

Please give me some help or tips since I do not know how to escape this.

Installing again Python3 this simple code DOES work on Sublime but still not on VS Code. I still get the same error in VS Code.

If I change from return to print and instead of shift-command debug and run the code then it works.

Any idea what is going on?


Solution

  • This looks like it's because you're running the code with Shift+ENTER.

    VS Code has the following 2 bindings for Shift_ENTER:

    enter image description here

    I believe that you're seeing the 2nd of these, which says "Run Selection/Line in Python Terminal. I suspect you have the focus on the return y line, and so it's only running that single line of code.

    If, instead of Shift+ENTER, you use the Run Code command in VS Code, you should see it work fine:

    enter image description here

    You might well think "OK...so if I select all of the code this will work, right?" and I agree...this feels like it should work. However, I see a similar issue. I'll see if I can work out why, but for the moment you can use the Run Code command in VS Code and that will do what you want. If you highlight the code you want to run, that will limit what gets executed.

    Run Code can be executed with Ctrl+Alt+N

    It looks like this issue (that selected code doesn't run correctly with Shift+ENTER) is a bug that's being tracked by here: https://github.com/Microsoft/vscode-python/issues/2837

    And a work around (not ideal) is to add code before/after your function that is NOT indented, and then select and execute those lines too:

    print("this...")
    
    def function(x):
        y = x + 2
        return y
    
    print("...now works if you select all these lines and Shift+ENTER!")