I'm running a Conda environment on VSCode and when I Shift-Enter to run main.py , a new Python terminal opens and runs the script, but functions are executing without being called and I'm getting a :
SyntaxError: 'return' outside function
Despite the indentation being seemingly fine.
import math
def h(x):
if x==0:
return 1
else:
return 2*math.sin(x)/x - 1
The above returns:
(base) josh@Joshs-Macbook Coursework1 % source /Users/josh/opt/anaconda3/bin/activate
(base) josh@Joshs-Macbook Coursework1 % conda activate base
(base) josh@Joshs-Macbook Coursework1 % /Users/josh/opt/anaconda3/bin/python
Python 3.8.8 (default, Apr 13 2021, 12:59:45)
[Clang 10.0.0 ] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> return 2*math.sin(x)/x - 1
File "<stdin>", line 1
SyntaxError: 'return' outside function
>>>
CodePudding user response:
You have executed the command of Run Selection/Line in Python Terminal
with the shortcut of Shift Enter
. You can select the command of Run Python File in Terminal
which is above it.
CodePudding user response:
Shift Enter
is keybindings for Run Selection/Line in Python Terminal, so if you put cursor in the line of return 2*math.sin(x)/x - 1
, it will throw errors:
If you want to enter interactive mode then run the function h(x)
, please
- type
python
in integrated Termial; - import filename. In my case, it's
a.py
so iimport a
; - call the function:
a.h(any number)
- exit interactive mode;
Or you can get result directly by adding print(h(any number))
, then clicking the triangle button in top right corner to run python file in integrated Terminal. Get the same result:
CodePudding user response:
run the entire code in python as opposed to the last line.
if you want to run entire scripts:
python3 xxxx.py