Python why does int("0") return false

Sven Fischer picture Sven Fischer · May 28, 2013 · Viewed 8.9k times · Source

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)

Answer

Elazar picture Elazar · May 28, 2013

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