4

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?

MSeifert
  • 145,886
  • 38
  • 333
  • 352
turnip
  • 2,246
  • 5
  • 30
  • 58

2 Answers2

7

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
MSeifert
  • 145,886
  • 38
  • 333
  • 352
0

True has value 1. If you set True = 5 (only in python 2) the equality become True. The 'if' statement is like it is checking if the guard is not 0 or None so every number not 0 is ok to enter in the first block. In fact False has value 0.

Mikedev
  • 316
  • 1
  • 8