Python : Why does False or 'name' returns 'name' and not False?
-
21-07-2021 - |
Question
AFAIK :
and
, or
are boolean operators and any boolean expression should return a boolean.
So, why does this happens :
False or 'name'
returns'name'
and notTrue
True and ''
returns''
and notFalse
Please explain, how does python handles boolean expressions ?
Solution
No, in python the or
and and
operations short circuit and return the last evaluated item.
See Boolean operations:
The expression
x and y
first evaluatesx
; ifx
is false, its value is returned; otherwise,y
is evaluated and the resulting value is returned.The expression
x or y
first evaluatesx
; ifx
is true, its value is returned; otherwise,y
is evaluated and the resulting value is returned.
If you must have a boolean value, use bool()
:
>>> bool(False or 'name')
True
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow