True/False value testing

Chris Angelico rosuav at gmail.com
Thu Jan 7 05:49:46 EST 2016


On Thu, Jan 7, 2016 at 9:36 PM, ast <nomail at invalid.com> wrote:
> Hello
>
> For integer, 0 is considered False and any other value True
>
>>>> A=0
>>>> A==False
>
> True
>>>>
>>>> A==True
>
> False
>>>>
>>>> A=1
>>>> A==False
>
> False
>>>>
>>>> A==True
>
> True
>
> It works fine
>
> For string, "" is considered False and any other value True,
> but it doesn't work
>
>>>> A = ""
>>>> A==False
>
> False
>>>>
>>>> A==True
>
> False
>>>>
>>>> A = 'Z'
>>>> A==False
>
> False
>>>>
>>>> A==True
>
> False
>
>
> What happens ???
>
> thx

There's a difference between "is considered false" and "is equal to
False". In Python, most collections are considered false if they are
empty:

def truthiness(x):
    if x:
        print(repr(x) + " is true")
    else:
        print(repr(x) + " is false")

truthiness([])
truthiness([1,2,3])
truthiness("")
truthiness("hello")
truthiness(0)
truthiness(73)
truthiness({})
truthiness({1:2, 3:4})

However, none of these will compare *equal* to the Boolean values True
and False, save for the integers 1 and 0. In fact, True is a special
form of the integer 1, and False is a special form of the integer 0;
they are considered to represent those numbers just as much as the
floating point values 1.0 and 0.0 do:

from decimal import Decimal
from fractions import Fraction
# Caveat, see footnote [1]
if Fraction(0, 1) == 0.0 == 0 == False == Decimal("0"):
    print("See? All representations of zero are equal")

Intuition tells you quite obviously that the integers 1 and 73 are not
equal, but both of them are very definitely truthy values. In the same
way, a non-empty list is truthy, but it's not equal to True.

Does that answer your question?

ChrisA

[1] In Python 2.7, Decimal("0") != Fraction(0, 1). I suspect this is a
bug, as it's been fixed in Python 3; both of them are equal to the
integer 0, but they're not equal to each other. So the order of checks
in that demo is actually significant.



More information about the Python-list mailing list