a
is a one-member tuple, which evaluates to True
. is
test identity of the object, therefore, you get False
in all those test. ==
test equality of the objects, therefore, you get False
again.
in if
statement a __bool__
(or __nonzero__
) used to evaluate the object, for a non-empty tuple it should return True
, therefore you get True
. hope that answers your question.
edit: the reason True
and False
are equal to 1
and 0
respectively is because bool
type implemented as a subclass of int
type.
Things in python don't have to be one of True
or False
.
When they're used as a text expression for if
/while
loops, they're converted to booleans. You can't use is
or ==
to test what they evaluate to. You use bool( thing )
>>> a = (None,)
>>> bool(a)
True
Also note:
>>> 10 == True
False
>>> 10 is True
False
>>> bool(10)
True
(None,) is a tuple that contains an element, it's not empty and therefore does not evaluate to False in that context.
In Python every type can be converted to bool
by using the bool()
function or the __nonzero__
method.
Examples:
False
when they are empty.False
when they are equal to 0.__nonzero__()
.[Edit]
In your code, the tuple (None,)
is converted using bool()
in the if
statements. Since it's non-empty, it evaluates to True
.
I find almost all the explanations here unhelpful, so here is another try:
The confusion here is based on that testing with "is", "==" and "if" are three different things.
And here comes the important part:
Now maybe this is only more clear in my head, but at least I tried. :)
Поскольку a = (None,)
является кортежем, содержащим единственный элемент None
Повторите попытку с a = None
и вы увидите другой результат.
Также попробуйте a = ()
, который является пустым кортежем. Это истинное значение ложно