Issue
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
Solution
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?
Answered By - Jeremy Brown
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.