-3

I have a function that is supposed to return false when lives are <= 0:

def isAlive(self):
    if self.lives <= 0:
       return False
    return True

But it always returns True.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
user2368334
  • 73
  • 1
  • 6

1 Answers1

2

I'm willing to bet that the actual problem is that lives isn't a number, but something else, such as the string '0', or the list [0].

In Python 2.x, when you compare values of incomparable types like this, it just compares the types.* So, every str or list is larger than every int. And therefore, no str or list is ever <= any int. As you can see from the interactive interpreter:

>>> '2' <= 2
False
>>> 'abcdefg' <= 2
False
>>> [2] <= 2
False

    >>> [] <= 2     False


To verify that this is the problem, and get started debugging it, try printing out both self.lives and type(self.lives) and see what you get. If it's not a number, with type int, that's what you have to fix.

The fix for this problem is to figure out how you ended up with the wrong type of value in self.lives earlier in the code, and whatever you're doing wrong there, don't do it.


* It isn't quite guaranteed that they're ordered by type, and the ordering of types itself definitely isn't guaranteed. But it doesn't matter anyway, because even if you did know the ordering, it's hard to imagine that you'd want to rely on it for anything useful.

abarnert
  • 354,177
  • 51
  • 601
  • 671