-1

First Mystery of Strings:
How come bool('foo') returns True?

if
'foo' == True returns False
'foo' == False returns False
'foo' is True returns False
'foo' is False returns False

Second Mystery of Integers:
How come bool(5) returns True?

if
5 == True returns False
5 == False returns False
5 is True returns False
5 is False returns False

Third Mystery of Zeros:
How come bool(0) returns False?

if
0 == True returns False
0 == False returns True <-- Special Case
0 is True returns False
0 is False returns False

I am aware of some of the truthiness of Python, however, this all seems a bit mysterious. Someone mind shedding some light on this?

2 Answers2

2

you need to read this: https://docs.python.org/2/library/stdtypes.html#truth-value-testing

'foo' == True  # -> False
'' == True     # -> False
'' == False    # -> False

will always be False. a string does not equal a bool. but - yes - bool('non-empty-str') -> True; bool('') -> False.

and so on for you other 'mysteries'.

is compares the identities id() of two objects (there are some mysteries here as well: What's with the Integer Cache inside Python?)

also this may be interesting: Is False == 0 and True == 1 in Python an implementation detail or is it guaranteed by the language?

Community
  • 1
  • 1
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
2

It is because both 0 and '' are False in Python, while non-empty strings and non-zero Integers are True.

In all of your examples the reason they are returning otherwise from your expectations is because == checks for the same value while is checks if the two point to the same object.

So in the first case, foo is True, but they are not the same value. As well, foo is not pointing to the same value as True which is why it returns false. The same pattern continues for the rest of the examples.

roflmyeggo
  • 1,724
  • 16
  • 18