Domanda

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)

È stato utile?

Soluzione

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

Altri suggerimenti

I think you meant i.isdigit() instead of int(i).

Because 0 is falsy, just like None, [], {} and False (and a few more objects). It's not explicitly false, but it evaluates to False when used as a condition.

If you want to check that i is a number, assume that it is a number:

try:
    n = int(i)
    print "That's a number"
except ValueError:
    print "That's not a number"
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top