Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Python evaluate strings/numbers as True in if statements yet myNumber == True returns False?

The following will print 'ok':

if 5:
   print('ok')

Yet when I do:

print(5 == True) 

The output is False.

The same thing happens with strings. Why?

like image 494
turnip Avatar asked Mar 08 '23 15:03

turnip


1 Answers

You're testing different things here.

The if just checks if the bool of the expression (see also "Truth value testing") is True not if the identity is equal to True.

So what is actually tested by the if is:

>>> bool(5) == True
True
like image 195
MSeifert Avatar answered Mar 12 '23 01:03

MSeifert