SyntaxError: ‘return’ outside function error occurs when you use the return statement outside the function. To fix this error, place the return statement inside the function definition, which makes it valid.
The error suggests that you are not using the return statement within the function because you are using it in the loop, and a function does not enclose that loop.
If you are trying to return a value from a script or module outside a function, consider alternative structures, such as assigning the value to a variable or printing it directly.
Reproduce the error
return 21
print("This code won't execute")
Output
SyntaxError: 'return' outside function
How to fix it?
def main_function():
return 21
print(main_function())
Output
21
Working with a while loop
When working in a loop, you mistakenly use the return statement to break the loop instead of using the break or quit() function.
while True:
return False
The above while loop should not have a return statement because it does not break the loop.
Stopping a while loop using the return statement does not make sense.
If you run the above code, you will get the following output.
return False
^
SyntaxError: 'return' outside function
To fix this error, create a function, write the loop inside that function, and then use the return function. This is the correct way to use the return.
def func():
while True:
return False
print(func())
Output
False
Don’t use the return statement to get out of the loop. If you do that, then you will face the SyntaxError. Instead, use the break or quit() to break the loop or terminate the program.
Don
Using onscreenclicks() in a function I want to exit the function (not the program after a number of clicks and return to the main part. Exitonclick(), exit, break, pass, return dont work. Some quit the prog but not the function. Snippet:
if clicks==4:
print(“get out”) #following dont work
#continue
#os._exit(n) same as
#turtle.exitonclick()
#return
#pass
#break