Greater than less than, python

北慕城南 提交于 2020-01-12 06:59:32

问题


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

回答1:


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?



来源:https://stackoverflow.com/questions/11767867/greater-than-less-than-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!