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
Summary. A comparison operator compares two values and returns a boolean value, either True or False . Python has six comparison operators: less than ( < ), less than or equal to ( <= ), greater than ( > ), greater than or equal to ( >= ), equal to ( == ), and not equal to ( !=
Well, to write greater than or equal to in Python, you need to use the >= comparison operator. It will return a Boolean value – either True or False. The "greater than or equal to" operator is known as a comparison operator. These operators compare numbers or strings and return a value of either True or False .
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With