简体   繁体   English

为什么无法在Python的`if __name__ ==“ __main __”`中执行return

[英]Why return can not be executed in `if __name__ == “__main__”` in Python

I am writing a program and I need the program to return a integer say changed to remind the controller that there are something changed.But when I want to return this value, I kept receiving this message: 我正在编写程序,我需要程序返回一个整数,并说`` changed以提醒控制器发生了一些changed ,但是当我想返回该值时,我一直收到以下消息:

 return 1
 SyntaxError: 'return' outside function

I have read some posts online they all said it is the indent problem but I am sure My indent is right because I have tried such a simple program but the failure still exists. 我已经在线阅读了一些帖子,他们都说这是缩进问题,但是我确信我的缩进是正确的,因为我已经尝试过这样一个简单的程序,但是失败仍然存在。

# -*- coding: utf-8 -*-


if __name__ == "__main__":
     return 1

here is the error message: 这是错误消息:

runfile('/home/iphyer/untitled1.py', wdir='/home/iphyer')
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "/usr/local/lib/python2.7/dist-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 699, in runfile
 execfile(filename, namespace)
  File "/usr/local/lib/python2.7/dist-packages/spyderlib/widgets/externalshell/sitecustomize.py", line 81, in execfile
builtins.execfile(filename, *where)
  File "/home/iphyer/untitled1.py", line 9
   return 1
  SyntaxError: 'return' outside function

Although my real programe is more complex than this but the structure is the same. 虽然我的实际程序比这复杂,但是结构是相同的。

I am confused because if I comment the return statement all program can be run without any warning. 我很困惑,因为如果我评论return语句,那么所有程序都可以在没有任何警告的情况下运行。

It is quit confusing. 这是令人困惑的。 I guess I can not using if __name__ == "__main__ for return some value? 我想我不能使用if __name__ == "__main__return一些值吗?

Thank you!~ 谢谢〜

The body of the if __name__ == "__main__": executes when the file in question is being run as a standalone program. if __name__ == "__main__":的主体if __name__ == "__main__":当相关文件作为独立程序运行时执行。 In that case, what you may want is exit() or sys.exit() which allow you to return limited information to the script that invoked this one. 在那种情况下,您可能想要的是exit()sys.exit() ,它们允许您将有限的信息返回给调用此脚本的脚本。 Typically you can either signal success with exit(0) or set of possible failures with a non-zero result (limited to 1 - 255). 通常,您可以通过exit(0)发出成功信号,或者以非零结果(限制为1-255)表示可能的失败集。 return is for subroutines/function, exit is for programs. return用于子例程/函数, exit用于程序。

Because if statement isn't a method. 因为if语句不是方法。 You can return only from methods in Python. 您只能从Python中的方法 return

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

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