The bool and int types in boolean contexts
I have this code in a boolean context:
True and False or 2
Output: 2
Type checking for this expression resulted in int
.
Then I changed the code to:
True and False or True
Output: True
And type checking for this expression resulted inbool
- Why is the output in the 1st code
2
? - Shouldn't you express an expression for a boolean value?
If not, why?
source to share
In Python, when using 'and' and 'or', the expression is evaluated using the objects involved instead of using Booleans as in many other languages.
So:
1 and 2 will evaluate to 2
1 or 2 will evaluate to 1 (short-circuit)
1 and "hello" will evaluate to "hello"
... etc.
If you want boolean, just surround the whole expression with bool (..)
Further reading: http://www.diveintopython.net/power_of_introspection/and_or.html https://docs.python.org/2/reference/expressions.html#boolean-operations
source to share
All you need to know is the definition of the OR
operand . Based on python documentation:
An x or y expression evaluates x first; if x is true, its value is returned; otherwise, y is evaluated and the return value is returned.
Since precedence is OR
less than and
, your expression is evaluated like this:
(True and False) or 2
Which is equal to the following:
False or 2
So, based on the previous documentation, the result will be the object's right value, which is 2.
source to share
When you said True and False
it is evaluated as False
. Then you have False or 2
one that will evaluate as will 2
now True and False or True
be evaluated before True
but last True
in your expression. This is due to operator precedence
>>> True and False
False
>>> False or 2
2
>>>
The output is 2
not True
because it True and False or 2
looks like
var = (True and False)
if var:
print(var)
else:
print(2)
what gives
2
because will True and False
always evaluate the valueFalse
source to share