Python return statement error “ 'return' outside function”

后端 未结 4 1066
别跟我提以往
别跟我提以往 2020-11-29 07:25

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

<
相关标签:
4条回答
  • 2020-11-29 07:34

    To break a loop, use break instead of return.

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

    0 讨论(0)
  • 2020-11-29 07:48

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

    0 讨论(0)
  • 2020-11-29 07:53

    The return statement only makes sense inside functions:

    def foo():
        while True:
            return False
    
    0 讨论(0)
  • 2020-11-29 07:54

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

    0 讨论(0)
提交回复
热议问题