I want to be able to find the highest value of three different variables with their own integer value assigned to them. These are my variables:
firstscore = 1
secondscore = 7
thirdscore = 8
I want to find which of these variables has the highest value. To do this I created this code:
if firstscore > secondscore:
if firstscore > thirdscore:
highestscore = firstscore
if thirdscore > firstscore:
highestscore = thirdscore
if secondscore > firstscore:
if secondscore > thirdscore:
highestscore = secondscore
if thirdscore > secondscore:
highestscore = thirdscore
if thirdscore > firstscore:
if thirdscore > secondscore:
highestscore = thirdscore
if secondscore > thirdscore:
highestscore = secondscore
This code works fine if I had thee differently numbered variables (like above), and so the variable 'highest score' would be equal to 8 (highest number was thirdscore). However, if I use three variables and two of them share the same value (for example: instead of 1, 7, 8 I had 8, 8, 3), the variable 'highest score' is always 0! Can anybody explain why this is happening and if there is a way to address this issue in my code? I'm sure it's a logical problem, but I haven't figured out. I just can't get my head around it!
I'm guessing that somewhere you initialize highestscore
to 0
. Your conditional statements only handle cases where every number is strictly greater than another, rather than greater than or equal. This means that if two of those variables are equal to each other, highestscore
doesn't get reassigned.
That said, the easiest way to find the highest score is as follows:
highestscore = max(firstscore, secondscore, thirdscore)
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