python and / or operators return value [duplicate]

自闭症网瘾萝莉.ら 提交于 2019-11-25 23:25:46

问题


This question already has an answer here:

  • How do “and” and “or” act with non-boolean values? 8 answers

I was watching a 2007 video on Advanced Python or Understanding Python, and at 18\'27\" the speaker claims \"As some may know in Python and and or return one of the two values, whereas not returns always a boolean.\" When has this been the case?

As far as I can tell, and and or return booleans, too.


回答1:


The and and or operators do return one of their operands, not a pure boolean value like True or False:

>>> 0 or 42
42
>>> 0 and 42
0

Whereas not always returns a pure boolean value:

>>> not 0
True
>>> not 42
False



回答2:


See this table from the standard library reference in the Python docs:




回答3:


from Python docs:

The operator not yields True if its argument is false, False otherwise.

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.

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.

Python's or operator returns the first Truth-y value, or the last value, and stops. This is very useful for common programming assignments that need fallback values.

Like this simple one:

print my_list or "no values"

This will print my_list, if it has anything in it. Otherwise, it will print no values (if list is empty, or it is None...).

A simple example:

>>> my_list = []
>>> print my_list or 'no values'
no values
>>> my_list.append(1)
>>> print my_list or 'no values'
[1]

The compliment by using and, which returns the first False-y value, or the last value, and stops, is used when you want a guard rather than a fallback.

Like this one:

my_list and my_list.pop()

This is useful since you can't use list.pop on None, or [], which are common prior values to lists.

A simple example:

>>> my_list = None
>>> print my_list and my_list.pop()
None
>>> my_list = [1]
>>> print my_list and my_list.pop()
1

In both cases non-boolean values were returned and no exceptions were raised.




回答4:


Need to add some points to the @Frédéric 's answer.

do return one of their operands???

It is True but that is not the logic behind this. In python a number except 0 is considered as True and number 0 is considered as False.

(0 and 42 -> False and True) = False.

That's why it returns 0.

(0 or 42-> false or True) = 42

In that case the statement will be True because of the operand 42. so python returns the operand which causes the statement to be true, in that case.



来源:https://stackoverflow.com/questions/4477850/python-and-or-operators-return-value

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