So, I was playing with the interpreter, and typed in the following:
In [95]: 1 and 2
Out[95]: 2
In [96]: 1 and 5
Out[96]: 5
In [97]: 234324 and 2
Out[97]: 2
In [98]: 234324 and 22343243242
Out[98]: 22343243242L
In [99]: 1 or 2 and 9
Out[99]: 1
Initially I thought that it has to do with False and True values, because:
In [101]: True + True
Out[101]: 2
In [102]: True * 5
Out[102]: 5
But that doesn't seem related, because False is always 0, and it seems from the trials above that it isn't the biggest value that is being outputted.
I can't see the pattern here honestly, and couldn't find anything in the documentation (honestly, I didn't really know how to effectively look for it).
So, how does
int(x) [logical operation] int(y)
work in Python?
Common logical operators include AND, OR, and NOT.
The logical AND operator ( && ) returns true if both operands are true and returns false otherwise. The operands are implicitly converted to type bool before evaluation, and the result is of type bool . Logical AND has left-to-right associativity.
The logical-AND operator produces the value 1 if both operands have nonzero values. If either operand is equal to 0, the result is 0. If the first operand of a logical-AND operation is equal to 0, the second operand isn't evaluated. The logical-OR operator performs an inclusive-OR operation on its operands.
Logical operators combine relations according to the following rules: The ampersand (&) symbol is a valid substitute for the logical operator AND . The vertical bar ( | ) is a valid substitute for the logical operator OR . Only one logical operator can be used to combine two relations.
From the Python documentation:
The expression
x and y
first evaluatesx
; ifx
is false, its value is returned; otherwise,y
is evaluated and the resulting value is returned.
Which is exactly what your experiment shows happening. All of your x
values are true, so the y
value is returned.
https://docs.python.org/3/reference/expressions.html#and
It's for every item in Python, it's not dependent on the integer.
not x Returns True if x is False, False otherwise
x and y Returns x if x is False, y otherwise
x or y Returns y if x is False, x otherwise
1 is True, so it will return 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With