53

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!

Jeff
  • 3,879
  • 3
  • 26
  • 28

4 Answers4

68

The return statement only makes sense inside functions:

def foo():
    while True:
        return False
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
31

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

Antonio
  • 19,451
  • 13
  • 99
  • 197
buzzard51
  • 1,372
  • 2
  • 23
  • 40
  • 1
    This works in case you just want to stop the script, as you would do with a void return. I'd rather use sys.exit() though, because then an exit status can be specified. Check this question: http://stackoverflow.com/questions/543309/programatically-stop-execution-of-python-script – Guillem Cucurull Feb 23 '16 at 15:41
12

To break a loop, use break instead of return.

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

Jürgen Strobel
  • 2,200
  • 18
  • 30
3

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

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378