I wrote some very simple code:
def yo():
text = "hi there"
print(text)
print(text)
yo()
I ran this in Spyder and online compilers without error. Obviously it spits out:
hi there
hi there
But when I run this in VS Code terminal using the "Run Python file in terminal" play button I get
"SyntaxError: invalid syntax"
for line 1 (the def line).
When I type yo()
into the terminal itself, I get the expected output of:
hi there
hi there
Why is do I get a different result from these? I executed other simple bits of Python in VS Code using the "play" button without issue. It goes without saying that I have the python extension and interpreter installed.
UPDATE: I restarted VS Code and now the file runs without issue. I guess "did you restart the computer" really does solve the issue sometimes...
CodePudding user response:
Your function - yo()
, is being defined, however Visual Studio Code does not know how to run it. To fix this, try adding the if __name__ == '__main__':
clause. Here is your full code:
def yo():
text = "hi there"
print(text)
print(text)
if __name__ == '__main__':
yo()
Here is some more information about if __name__ == '__main__':
If that doesn't fix it, you must have some formatting issues or some different settings of Visual Studio Code. You could do the following things.
- Make sure you're running the right file
- Delete all of the code and paste it in again
- Reset your Visual Studio Code settings
- Make sure your settings for Tab are 4 spaces.
- Disable
terminal.integrated.inheritEnv
in Settings
If all else fails, try these:
You should use the exit()
command in the terminal to end python session. Then re-run and see if anything works.
Run your code using 'Start without debugging'.