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

The following will print 'ok':

if 5:
   print('ok')

But when I do this:

print(5 == True) 

Output signal False.

The same thing happens with strings. Why?

+4
source share
2 answers

Here you test different things.

ifjust checks if the expression of the boolexpression (see also "Checking the value of truth" ) is Truenot if the identity is equal True.

So what is actually verified if:

>>> bool(5) == True
True
+7
source

True 1. True = 5 ( python 2), True. "if" , , 0 , 0 . False 0.

0

Source: https://habr.com/ru/post/1681189/


All Articles