Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between "if x == True" and "if x:" [duplicate]

Tags:

python

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"?

like image 324
Matthias Heppner Avatar asked Sep 19 '19 07:09

Matthias Heppner


3 Answers

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.

like image 172
glglgl Avatar answered Nov 10 '22 02:11

glglgl


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:
like image 30
Barmar Avatar answered Nov 10 '22 01:11

Barmar


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"
like image 2
kederrac Avatar answered Nov 10 '22 01:11

kederrac