Search code examples
pythonstringbooleanevaluationtruthiness

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?


Solution

  • 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