0

Possible Duplicate:
Why does “[] == False” evaluate to False when “if not []” succeeds?

How is this possible that logical test a==True produces False, but if a: works? Please see code below

>>> a = bin(0)
>>> if a:
    print a == True, 'HOWWWW???????'


False HOWWWW???????
>>> type(a)
<type 'str'>
>>> 
John Bollinger
  • 160,171
  • 8
  • 81
  • 157
dccharacter
  • 421
  • 1
  • 4
  • 14
  • Python has a short list of expressions which are evaluated to false in this documentation: http://docs.python.org/2/library/stdtypes.html#truth-value-testing – Will C. Dec 27 '12 at 20:25

3 Answers3

5

An if statement doesn't depend on whether the value is equal to true. It depends on whether bool(a) is equal to True, which in this case it is. Nonempty strings are considered true in a boolean context. See the documentation.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
0

OK, it seems in python you can't test a string this way:

>>> a == False
False
>>> a == True
False
>>> 
dccharacter
  • 421
  • 1
  • 4
  • 14
  • 1
    Why not? A string will never be equal to True or False, because neither True nor False is a string. At least it doesn't raise an exception! – Mark Ransom Dec 27 '12 at 20:22
0

for a string a , if a is equivalent to if len(a)!=0

gefei
  • 18,922
  • 9
  • 50
  • 67