-2

I was thinking if we were checking the boolean of string or character, we were checking if they were empty. But the following code gave me unexpected outputs.

print('0'==True)
print("0"==True)

Output:

False
False

What is happening? What we were really checking?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Lusha Li
  • 1,068
  • 2
  • 11
  • 22

4 Answers4

5

They are true (in a boolean context):

if '0':
    print("you will see this")
if '': # for comparison
    print("you will not see this")
# Alternately:
bool('0') # True
bool('') # False

But they are not equal to the special value True.

There is no contradiction.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
2

You must be thinking of languages that convert operands to a common type before checking for equality. This is not how Python works. As you can read here, the rules for equality are pretty complex; but they boil down to this:

The default behavior for equality comparison (== and !=) is based on the identity of the objects.

So all non-empty strings are "interpreted as true" (as are most objects, other than empty containers and a couple of constants); but they are not equal to each other, and they are not equal to the constant True.

"Interpreted as true" basically means that they make a conditional come out true, and that conversion to boolean (with bool()) will give the value True.

PS. Just for fun, note that the following does hold:

>>> print(1 == True)
True

Yes, the constant True just happens to be equal to the integer 1. Why not?

alexis
  • 48,685
  • 16
  • 101
  • 161
0

if you compare this:

print('0'==False) # False
print("0"==False) # False

so they are not giving false, you are comparing if a '0' is equal to True which is false but if you are doing something like

if '0':
   print("true") # this will be printed
basilisk
  • 1,156
  • 1
  • 14
  • 34
0

'0' is a string, which is not empty. For strings, only empty string is falsy i.e. '':

In [239]: bool('0')                                                                  
Out[239]: True

In [240]: bool('')                                                            
Out[240]: False

And for truthy/falsey test, you can just do:

if <some_value>:

no need to check against any other value. This is applicable for all types.

heemayl
  • 39,294
  • 7
  • 70
  • 76