Skip to content Skip to sidebar Skip to footer

Python: Finding Which Variable Has The Highest Value And Assign That Value To A New Variable

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 third

Solution 1:

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)

Solution 2:

the easiest way to do this, is:

highestscore = max(firstcore, secondscore, thirdscore)

However, I would recommend to have all values in a list, e.g.

a = [5, 2, 9, 23, 89, 42, 23, 49, 0, -3, -7]

and then do

highestscore = max(a)

The answer to your question, why your highestscore is always 0, is because you check only for greater than (and 8 is equal, or greater equal 8). That's why you don't go into any of you if paths. Max is better, because of the simplicity and and can handle infinite number of arguments, instead of only three (four, five, six, ...). Also it's less error prone, because you have much less code ;)

Solution 3:

First, the most pythonic way to write the same thing would be:

highestscore = max((firstscore, secondscore, thirdscore))

Second, the code in the question is just wrong. You need to use else statements.

Post a Comment for "Python: Finding Which Variable Has The Highest Value And Assign That Value To A New Variable"