What does Python return when we return with logical operator?

五迷三道 提交于 2019-12-11 02:56:07

问题


I was reading someone else's code and he had something like this:

return val1 and val2 

I tried this in the Python interpreter and it gave me the latter value on AND while OR gives me the prior value.

So my question is what exactly is happening in that statement?

Thanks.


回答1:


An expression using and or or short-circuits when it can determine that the expression will not evaluate to True or False based on the first operand, and returns the last evaluated value:

>>> 0 and 'string'
0
>>> 1 and 'string'
'string'
>>> 'string' or 10
'string'
>>> '' or 10
10

This 'side-effect' is often used in python code. Note that not does return a boolean value. See the python documentation on boolean operators for the details.




回答2:


An AND statement is equal to the second value if the first value is true. Otherwise it is equal to the first value.

An OR statement is equal to the first value if it is true, otherwise it is equal to the second value.

Note that in Python an object can be evaluated to a boolean value. So "bla" and False will evaluate to the second value because the first value is true (it is a non-empty string and bool("string") = True).

This is how boolean statements are evaluated in Python (and multiple other programming languages). For example:

  • True and False = False (equal to second value because the first value is true)
  • False and True = False (equal to the first value because the first value is not true)
  • True and True = True (equal to the second value because the first value is true)
  • True or False = True (equal to the first value because it is true)
  • False or True = True (equal to the second value)


来源:https://stackoverflow.com/questions/11920972/what-does-python-return-when-we-return-with-logical-operator

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