What is the difference between "if x == True" and "if x:"
The ==
operator doesn't compare the truthiness of its operands, it compares their values.
When boolean values are used in a context that requires numbers, such as when comparing them with numbers, they get converted automatically: True
becomes 1
, False
becomes 0
.
So
if some_boolean == some_number:
is effectively equivalent to:
if int(some_boolean) == some_number:
This is why
if True == 2:
does not succeed. int(True)
is 1
, so this is equivalent to
if 1 == 2:
equivalent ways to look at the problem:
"if x" <==> "if bool(x)"
since your x is an integer:
"if x" <==> "if x != 0"
and
"if x == True" <==> "if x == 1"
The difference is that if x:
checks the truth value of x
. The truth value of all integers except 0 is true (in this case, the 2).
if x == True:
, however, compares x
to the value of True
, which is a kind of 1
. Comparing 2 == 1
results in a false value.
To be exact, there are two adjacent concepts:
* the one is the "truth value", which determines the behaviour of if
, while
etc.
* the other are the values True
and False
, which have the respective truth values "true" and "false", but are not necessary equal ot other true resp. false values.
If you absolutely need to check for the exact values of True
and False
for whatever reason, you can do so with if x is True
or if x is False
. This ensures that if y is exactly True
will pass the test, if it is 1
, it won't.