Reputation: 1139
In my program encountered with this:
>>> True and True and (3 or True)
3
>>> True and True and ('asd' or True)
'asd'
while I expected to get some boolean value depending on the result in brackets. So if I try comparisons like these (0 or True)
or ('' or True)
python will return True
, which is clear because 0
and ''
equivalent to False
in comparisons.
Why doesn't python return boolean value by converting 3
and 'asd'
into True
?
Upvotes: 1
Views: 2409
Reputation: 1406
From https://docs.python.org/3/library/stdtypes.html:
Important exception: the Boolean operations or and and always return one of their operands
The behavior can be most easily seen with:
>>> 3 and True
True
>>> True and 3
3
If you need to eliminate this behavior, wrap it in a bool:
>>> bool(True and 3)
True
See this question
As Reut Sharabani, answered, this behavior allows useful things like:
>>> my_list = []
>>> print (my_list or "no values")
Upvotes: 4