How do I find the maximum (larger, greater) of 2 numbers?

Question:

I have two variables value and run:

value = -9999
run = problem.getscore()

How can I find out which one is greater, and get the greater value?


See also Find the greatest (largest, maximum) number in a list of numbers – those approaches work (and are shown here), but two numbers can also be compared directly.

Asked By: Shilpa

||

Answers:

max(number_one, number_two)

Answered By: dave

You can use max(value, run)

The function max takes any number of arguments, or (alternatively) an iterable, and returns the maximum value.

Answered By: Chris B.
max(value,run)

should do it.

Answered By: Tim Pietzcker

Use the builtin function max.

Example:
max(2, 4) returns 4.

Just for giggles, there’s a min as well…should you need it. 😛

Answered By: Ashley Grenon

Just for the fun of it, after the party has finished and the horse bolted.

The answer is: max() !

Answered By: Muhammad Alkarouri

I noticed that if you have divisions it rounds off to integer, it would be better to use:

c=float(max(a1,...,an))/b

Sorry for the late post!

Answered By: Ivranovi
numberList=[16,19,42,43,74,66]

largest = numberList[0]

for num2 in numberList:

    if num2 > largest:

        largest=num2

print(largest)

gives largest number out of the numberslist without using a Max statement

Answered By: Ryan

(num1>=num2)*num1+(num2>num1)*num2 will return the maximum of two values.

Answered By: Mason

You could also achieve the same result by using a Conditional Expression:

maxnum = run if run > value else value

a bit more flexible than max but admittedly longer to type.

# Python 3
value = -9999
run = int(input())

maxnum = run if run > value else value
print(maxnum)
Answered By: Nages

There are multiple ways to achieve this:

  1. Custom method
def maximum(a, b):
if a >= b:
    return a
else:
    return b
 
value = -9999
run = problem.getscore()
print(maximum(value, run))
  1. Inbuilt max()
value = -9999
run = problem.getscore()
print(max(value, run))
  1. Use of ternary operator
value = -9999
run = problem.getscore()
print(value if value >= run else run)

But as you mentioned you are looking for inbuilt so you can use max()

Answered By: svikramjeet
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.