11

I am doing a ranking type thing, what happens is I compare the score to the current score and if the score is lower then the current then the player has got a high score, but when using this code here

        print "Score = " + str(score) + ", Compared to = " + str(array[x])
        if score < array[x]:
                #Do stuff here

But even if score is 4 and array[x] is 2 the if statement is still done?

Am I doing something wrong?

My understanding is that if score 4 and array[x] is 2 then 4 is greater than 2 which means it comes back False?


Heres the full code

def getRank(array, score):
    rank = 0
    rankSet = False
    for x in range(0, len(array)):
        print "Score = " + str(score) + ", Compared to = " + str(array[x])
        if score < array[x]:
            if not rankSet:
                rank = x
                print "Set rank to: " + str(rank)
                rankSet = True
        elif score == array[x] or score > array[x]:
            rank += 1
            print "Rank higher than " + str(x)
    print "Rank = " + str(rank)
    return rank

it prints this if score = 4 and the array is made up of [1, 2]

Score = 4, Compared to = 1
Set rank to: 0
Score = 4, Compared to = 2
Rank = 0
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
FabianCook
  • 20,269
  • 16
  • 67
  • 115

1 Answers1

24

Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.

>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False

Edit

Further explanation: How does Python compare string and int?

Community
  • 1
  • 1
Jeremy Brown
  • 17,880
  • 4
  • 35
  • 28
  • 3
    Easiest way to check: `print repr(score), repr(array[x])`. Also: in Python 3, you get `TypeError: unorderable types: int() < str()`; this is only a 2.x problem. – Danica Aug 01 '12 at 21:33