Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: finding which variable has the highest value and assign that value to a new variable

Tags:

python

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!

like image 794
Elian Xavier Avatar asked Dec 19 '22 03:12

Elian Xavier


1 Answers

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)
like image 148
TigerhawkT3 Avatar answered Dec 22 '22 00:12

TigerhawkT3