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())
Output
21
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())
Output
False
You can see that we fixed the error and got the expected output.
That’s it.
Further reading

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
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