Using OR operator in python lambda function

The Python programming book O Reilly has sample code that uses the OR operator in a lambda function. The text states that "[code] uses the or operator to force two expressions to run."

How and why does it 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()

      

+3


source to share


2 answers


Every function in Python returns a value. If there is no explicit return statement, it returns None

. None

because the boolean expression evaluates to False

. Thus, print

returns None

, and the right side of the expression is or

always evaluated.



+2


source


The Boolean operator or

returns the first available truth value, evaluating candidates in sequence from left to right. So in your case, it is used to print first 'Hello lambda world'

as it returns None

(considered false), then it will evaluate sys.exit()

which terminates your program.

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

      




Python documentation :

The expression x or y

evaluates first x

; if x

true, its value is returned; otherwise it is evaluated y

and the resulting value is returned.

+2


source







All Articles