Python return statement error " 'return' outside function"


Question

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!

1
34
10/20/2011 8:54:35 PM

Accepted Answer

The return statement only makes sense inside functions:

def foo():
    while True:
        return False
49
10/20/2011 9:05:09 PM

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


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon