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