54

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!

3
  • 16
    What the interpreter says, you're not inside a function. Control statements aren't functions, you define a function with def. Commented Oct 20, 2011 at 20:56
  • 2
    You're probably looking for break. Commented Oct 20, 2011 at 21:06
  • I use yield which gives me the same error, reason is the same, shall be in a function.. Commented Jul 29, 2014 at 9:41

4 Answers 4

69

The return statement only makes sense inside functions:

def foo():
    while True:
        return False
Sign up to request clarification or add additional context in comments.

5 Comments

Raymond, did you get so many rep points that your counter rolled back over to 0?
@PaulMcGuire: your comment confuses me.
@PaulMcGuire His account has only existed for three days.
I will be naming name my first child @Raymond-Hettinger
I have been losing sleep over this
36

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

1 Comment

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: stackoverflow.com/questions/543309/…
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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.