SyntaxError: ‘return’ outside function error occurs in Python when you “use the return statement outside the function.” SyntaxError 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.
To fix the SyntaxError: ‘return’ outside function error, “place the return statement inside the function definition, which makes it valid.”
Don’t use the return statement to get out of the loo in Pythonp. If you do that, then you will face the SyntaxError. Instead, use the break or quit() statement to break the loop or terminate the program.
Reproduce the error
return 21 print("This code won't execute")
It throws the SyntaxError: ‘return’ outside function error because we use the ‘return’ statement outside the function definition.
How to fix SyntaxError: ‘return’ outside function
Always use the ‘return’ statement inside the function definition to fix the SyntaxError: ‘return’ outside function error in Python.
def main_function(): return 21 print(main_function())
While 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.
For example, see the below code.
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 senset.
If you run the above code, you will get the following output.
return False ^ SyntaxError: 'return' outside function
We get the SyntaxError: ‘return‘ outside function.
How to fix the SyntaxError while working with a while loop
To fix the return outside function SyntaxError in Python, 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())
You can see that we fixed the error and got the expected output.