[英]Why 10 and 5 returns 5 and 5 and 10 returns 10 in python? Basically it returns the second int after and operator irrespective of value
I was looking into python "and" operator and found out:我正在研究python“and”运算符并发现:
>>> 10 and 5
5
>>> 5 and 10
10
Think of statement logic and which operand determines the value of the entire expression:想想语句逻辑以及哪个操作数决定了整个表达式的值:
and
: and
:False
regardless of what comes afterFalse
Examples:例子:
>>> 5 and 0
0
>>> 0 and 5
0
>>> 5 and 0 and 3
0
>>> 10 and 5
5
>>> 5 and 10
10
or
: or
:True
regardless of what comes afterTrue
Examples:例子:
>>> 5 or 0
5
>>> 0 or 5
5
>>> 5 or 0 or 3
5
>>> 10 or 5
10
>>> 5 or 10
5
Note that the rest of the expression is not even evaluated, which is relevant if you chain egfunction calls or other expressions with side effects:请注意,表达式的其余部分甚至不会被计算,如果您将 egfunction 调用或其他具有副作用的表达式链接起来,这很重要:
>>> 4/0 or 5
ZeroDivisionError
>>> 5 or 4/0
5
>>> func1() or func2() and func3()
# func2 and func3 might never be called
This is kind of directly required for the short-circuit behaviour, but not completely intuitive, especially compared to Python's arithmetic operators:这是短路行为的直接要求,但并不完全直观,尤其是与 Python 的算术运算符相比:
a or b and c or d == (a or (b and (c or d)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.