在python lambda函数中使用OR运算符

2024-05-16 08:29:47 发布

您现在位置:Python中文网/ 问答频道 /正文

在O Reilly编程Python书籍中有一个代码示例,它在lambda函数中使用OR运算符。文本声明“[代码]使用or运算符强制运行两个表达式”。在

这是怎么工作的?为什么?在

widget = Button(None, # but contains just an expression
text='Hello event world',
command=(lambda: print('Hello lambda world') or sys.exit()) )
widget.pack()
widget.mainloop()

Tags: orlambda函数代码文本声明示例hello
2条回答

Python中的每个函数都返回一个值。如果没有显式的return语句,则返回NoneNone作为布尔表达式计算结果为False。因此,print返回None,并且始终计算or表达式的右侧。在

布尔or运算符通过按从左到右的顺序计算候选值,返回第一个出现的truthy值。所以在您的例子中,它首先用于打印'Hello lambda world',因为它返回None(被认为是错误的),然后它将计算sys.exit(),从而结束程序。在

lambda: print('Hello lambda world') or sys.exit()

Python Documentation

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

相关问题 更多 >