Python return statement error " 'return' outside function"

Python

Python Problem Overview


When running the following code (in Python 2.7.1 on a mac with Mac OS X 10.7)

while True:
    return False

I get the following error

SyntaxError: 'return' outside function

I've carefully checked for errant tabs and/or spaces. I can confirm that the code fails with the above error when I use the recommended 4 spaces of indentation. This behavior also happens when the return is placed inside of other control statements (e.g. if, for, etc.).

Any help would be appreciated. Thanks!

Python Solutions


Solution 1 - Python

The return statement only makes sense inside functions:

def foo():
    while True:
        return False

Solution 2 - Python

Use quit() in this context. break expects to be inside a loop, and return expects to be inside a function.

Solution 3 - Python

To break a loop, use break instead of return.

Or put the loop or control construct into a function, only functions can return values.

Solution 4 - Python

As per the documentation on the return statement, return may only occur syntactically nested in a function definition. The same is true for yield.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJeffView Question on Stackoverflow
Solution 1 - PythonRaymond HettingerView Answer on Stackoverflow
Solution 2 - Pythonbuzzard51View Answer on Stackoverflow
Solution 3 - PythonJürgen StrobelView Answer on Stackoverflow
Solution 4 - PythonEugene YarmashView Answer on Stackoverflow