Python programs / Numbers / Largest of three numbers

Python Program to Find the Largest of Three Numbers

Beginner Numbers

Finds the largest of three numbers by comparing them with if, elif and else.

The largest of three numbers is the one at least as big as both of the others. Of 12, 45 and 7 it's 45, since 45 ≥ 12 and 45 ≥ 7. It's a classic first exercise for if, elif and else, and Python's max() does the same in one call.

Program

def largest_of_three(a, b, c):
    """The largest of the numbers a, b and c."""
    if a >= b and a >= c:
        return a
    elif b >= c:
        return b
    else:
        return c


print("Largest of 80, 15, 33:", largest_of_three(80, 15, 33))
print("Largest of 12, 45, 7:", largest_of_three(12, 45, 7))
print("Largest of -4, -9, -2:", largest_of_three(-4, -9, -2))

Open in the editor Download largest_of_three.py

Output

Largest of 80, 15, 33: 80
Largest of 12, 45, 7: 45
Largest of -4, -9, -2: -2

How it works

  1. If a is at least as big as both b and c, it's the largest. and means both comparisons have to be true.
  2. elif is tested only when the if was false. Then a isn't the largest, so the answer is b or c, and one comparison between them is enough: if b is at least as big as c, it's b.
  3. Otherwise c is the largest.
  4. The program tries three sets of numbers, with the largest first, second and third, so each branch runs once. The last set shows that negative numbers work too: -2 is the largest of -4, -9 and -2.

Other ways to write it

With max()

Python's built-in max() returns the largest of any number of values, or of a list, so the function becomes one line. It's what you'd use in real code.

def largest_of_three(a, b, c):
    return max(a, b, c)

print(largest_of_three(12, 45, 7))
print(max([3, 18, 27, 9, 14]))

With a running largest

Start by taking the first number as the largest, then replace it whenever a bigger one comes along. This is the idea behind max() on a list, and it grows to four or more numbers with one more if for each.

def largest_of_three(a, b, c):
    largest = a
    if b > largest:
        largest = b
    if c > largest:
        largest = c
    return largest

print(largest_of_three(12, 45, 7))

Try it yourself

  • Try a tie for the largest, such as 30, 8 and 30, and three equal numbers.
  • Write smallest_of_three the same way with <=, and check its answers against min().
  • Compare decimals such as 2.5, 2.75 and 2.6, and words such as "pear", "apple" and "plum": for text, >= goes by alphabetical order, so "plum" is the largest.
  • Find the largest of four numbers with the running largest.

More numbers programs

Share this program