I thought I understood these two singleton values in Python until I saw someone using return l1 or l2
in the code, where both l1 and l2 are linked list object, and (s)he wanted to return l1 if it is not None, otherwise, return l2.
This piece of code is good because it is quite short and seems easy to understand. Then, I write some code to figure out what is going one here.
print ( True or 'arbitrary' ) #True
print ( False or 'arbitrary') #arbitrary
print ( None or 'arbitrary' ) #arbitrary
The printed results are as expected. However, when I try to put None
and False
together. Something really weird happened.
print ( False or None ) #None
print ( None or False ) #False
print ( None or False or True) #True
So, my guess the rules of return A or B
are:
return the first True (not None, Not False) value in order (First A and then B)
if there is no True value, then the last value will be returned.
At last, I run this code to verify my guess.
print ( None or False or True or None) # True
print ( None or False or None) # None
print ( False or None or False) # False
The results seem to prove my theory. But anyone has more explanation?
Also, I got something interesting when I use and
. Why?
print ( None and False) #None
print ( False and None) #False