简体   繁体   English

Python return语句错误“'return'外部函数”

[英]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) 运行以下代码时(在Mac OS X 10.7的Mac上为Python 2.7.1)

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. 当我使用推荐的4个缩进空格时,可以确认代码失败并出现上述错误。 This behavior also happens when the return is placed inside of other control statements (eg if, for, etc.). 当将返回值置于其他控制语句内时(例如,if,for等),也会发生此行为。

Any help would be appreciated. 任何帮助,将不胜感激。 Thanks! 谢谢!

The return statement only makes sense inside functions: return语句仅在函数内部有意义:

def foo():
    while True:
        return False

Use quit() in this context. 在这种情况下使用quit() break expects to be inside a loop, and return expects to be inside a function. break期望在循环内,而return期望在函数内。

To break a loop, use break instead of return . 要中断循环,请使用break而不是return

Or put the loop or control construct into a function, only functions can return values. 或将循环或控件构造放入函数中,只有函数可以返回值。

As per the documentation on the return statement, return may only occur syntactically nested in a function definition. 根据return语句的文档, return只能在语法上嵌套在函数定义中。 The same is true for yield . yield也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM