148

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.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Shilpa
  • 1,815
  • 3
  • 19
  • 23

12 Answers12

330

Use the builtin function max.

Example: max(2, 4) returns 4.

Just for giggles, there's a min as well...should you need it. :P

phoenix
  • 7,988
  • 6
  • 39
  • 45
Ashley Grenon
  • 9,305
  • 4
  • 41
  • 54
31

max()

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
21

max(number_one, number_two)

dave
  • 12,406
  • 10
  • 42
  • 59
9

You can use max(value, run)

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

Chris B.
  • 85,731
  • 25
  • 98
  • 139
9
max(value,run)

should do it.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
5

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.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
4

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

The answer is: max() !

Muhammad Alkarouri
  • 23,884
  • 19
  • 66
  • 101
3

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

Mason
  • 39
  • 1
1

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!

Michael W
  • 690
  • 1
  • 9
  • 22
Ivranovi
  • 74
  • 5
1
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

Suever
  • 64,497
  • 14
  • 82
  • 101
Ryan
  • 11
  • 1
0
# Python 3
value = -9999
run = int(input())

maxnum = run if run > value else value
print(maxnum)
Nages
  • 763
  • 1
  • 9
  • 12
  • While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – Buddy Bob Jun 08 '21 at 17:52
0

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()

svikramjeet
  • 1,779
  • 13
  • 27