Jeff
Jeff

Reputation: 4037

Python return statement error " 'return' outside function"

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!

Upvotes: 54

Views: 244056

Answers (4)

buzzard51
buzzard51

Reputation: 1477

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

Upvotes: 35

Eugene Yarmash
Eugene Yarmash

Reputation: 150188

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

Upvotes: 3

Jürgen Strobel
Jürgen Strobel

Reputation: 2248

To break a loop, use break instead of return.

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

Upvotes: 12

Raymond Hettinger
Raymond Hettinger

Reputation: 226754

The return statement only makes sense inside functions:

def foo():
    while True:
        return False

Upvotes: 69

Related Questions