Search code examples
pythonvalidationintstring-conversion

Python why does int("0") return false


I am trying to learn Python and can, for the life of it, not figure out, why this:

i = raw_input("enter a number")

if int(i):
    print "yes"
else:
    print "false"

would not return true if i == "0"

Background: I am trying to implement Union-Find Algorithm. Everything works fine, but when I try to connect two points and one is 0 it won't let me through the control. (Python 2.7)


Solution

  • Python types has boolean value, defined in special methods. in particular, 0, None, False, "" (and any other empty sequence) are false.

    Obviously,

    >>> int("0")
    0
    

    What's more, the value of False is 0, and the value of True is 1, for most purposes (except for their representation as strings, and their type, which is bool):

    >>> 0 == False
    True