Hello stackoverflow Community :-)
I am learning Python at the moment and I don't understand the "True/False" concept entirely.
In Python the number 0 is associated to "False" and 1 to "True".
When I write following code
x = 2
y = 1
if y == True:
print("Y is True")
if x == True:
print("X is True")
else:
print("X is False")
I get "Y is True", because the "1" is truthy. And I get "X is false", but I thought that this should be also "True", because there is a value (x = 2) and not "None, 0, etc.."
When I write
if x:
print("X is True")
else:
print("X is False")
then I get "X is True", because x is not empty and thus truthy.
What is the exact difference between "if x:" and "if x == True"?
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With