How to understand the result of `None or False`, `False or None`, `None and False`, `False and None` in Python?

孤街浪徒 提交于 2020-06-07 03:55:06

问题


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

回答1:


The short answer is that 'and' returns the first false value or last true value and 'or' returns the first true or last false answer.

>>> None or False
False
>>> False or None
>>> False and None
False
>>> None and False

...

>>> 0 or 3 or 4
3
>>> 5 and 0 and 6
0
>>> 5 and 0 or 6
6
>>> False or {} or 0
0
>>> 3 and 4 and 5
5



回答2:


In python an empty string, set, list, dictionary, other container or 0 are all equivalent to False for logical operations. Non-empty collections and non-zero numbers are logically True.

For an 'or' the last expression will be returned if no logically True expression was previously encountered. That expression will logically evaluated by the above rule.




回答3:


No need to guess. For or, Python's Reference Manual says

"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."

In other words, x if x else y, where x is evaluated just once and y only if needed.

For and, change 'true' to 'false'.

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

In other words, x if not x else y, where x is evaluated just once and y only if needed.



来源:https://stackoverflow.com/questions/47879272/how-to-understand-the-result-of-none-or-false-false-or-none-none-and-fals

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