Use of OR operator in python lambda function

孤者浪人 提交于 2021-02-07 06:50:15

问题


There is a code example in the O Reilly Programming Python book which uses an OR operator in a lambda function. The text states that "[the code] uses an or operator to force two expressions to be run".

How and why does this work?

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()

回答1:


Every funnction in Python returns a value. If there is no explicit return statement it returns None. None as boolean expression evaluates to False. Thus, print returns None, and the right hand side of the or expression is always evaluated.




回答2:


The Boolean or operator returns the first occurring truthy value by evaluating candidates in sequence from left to right. So in your case, it is used to first print 'Hello lambda world' since that returns None (considered falsey), it will then evaluate sys.exit() which ends your program.

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.



来源:https://stackoverflow.com/questions/44321085/use-of-or-operator-in-python-lambda-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!