How to Fix SyntaxError: ‘return’ outside function in Python

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




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




You can see that we fixed the error and got the expected output.

That’s it.

Further reading

Python return 0

Python return null

1 thought on “How to Fix SyntaxError: ‘return’ outside function in Python”

  1. 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
    #os._exit(n) same as


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.