Python返回语句错误"“返回"外部函数" [英] Python return statement error " 'return' outside function"

查看:61
本文介绍了Python返回语句错误"“返回"外部函数"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行以下代码时(在 Mac OS X 10.7 的 Mac 上使用 Python 2.7.1)

When running the following code (in Python 2.7.1 on a mac with Mac OS X 10.7)

while True:
    return False

我收到以下错误

SyntaxError: 'return' outside function

我已经仔细检查了错误的制表符和/或空格.当我使用推荐的 4 个缩进空格时,我可以确认代码失败并出现上述错误.当 return 放在其他控制语句(例如 if、for 等)中时,也会发生这种行为.

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!

推荐答案

return 语句只在函数内部有意义:

The return statement only makes sense inside functions:

def foo():
    while True:
        return False

这篇关于Python返回语句错误"“返回"外部函数"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆