Find Largest of Three Numbers in Python
a vs b vs c. Use >= so ties don't fall through into the wrong variable.
BeginnerBasic Python ProgramsExample 7 of 25
find-largest-of-three-numbers.py
1# Program to find the largest of three numbers23a = float(input("Enter first number: "))4b = float(input("Enter second number: "))5c = float(input("Enter third number: "))67if a >= b and a >= c:8 largest = a9elif b >= a and b >= c:10 largest = b11else:12 largest = c1314print("Largest number is:", largest)
Output
Enter first number: 10 Enter second number: 25 Enter third number: 7 Largest number is: 25.0
In this one
- >=, not >, when ties are allowed
- max() exists; this is so you can write it by hand
What's going on
Two numbers were if / elif / else. Three numbers is the same idea with and.
a >= b and a >= c — if that's true, a wins, including ties. Use > instead of >= and two equal maxima pick the wrong one.
max(a, b, c) is shorter. Write the comparisons once so the logic is in your head, not only in the builtin.
After this program
If the idea is still fuzzy, read Day 1: Introduction to Python in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 basic python programs, or see every topic on Python exercises.