What You'll Learn
- •Chaining relational operators with and
- •Extending comparison logic to three values
- •Using elif branches to cover multiple conditions
Python
# Program to find the largest of three numbers
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
c = float(input("Enter third number: "))
if a >= b and a >= c:
largest = a
elif b >= a and b >= c:
largest = b
else:
largest = c
print("Largest number is:", largest)Output
Enter first number: 10 Enter second number: 25 Enter third number: 7 Largest number is: 25.0
Find Largest of Three Numbers in Python
We extend the comparison logic to three numbers using a combination of >= and logical operators and.
Logical Operators
and- returns True if both conditions are Trueor- returns True if at least one condition is Truenot- reverses the boolean value
Comparison Strategy
We check:
- If
ais greater than or equal to bothbandc. - Else if
bis greater than or equal to bothaandc. - Otherwise,
cmust be the largest (or tied for largest).
This pattern generalizes the two-number comparison approach.
Program Logic
pythonif a >= b and a >= c: largest = a elif b >= a and b >= c: largest = b else: largest = c
Key Takeaways
1
Use
and to combine multiple conditions2
>= handles equality cases automatically3
This pattern can be extended to more numbers
4
Storing result in a variable makes code cleaner
Step-by-Step Breakdown
- 1Read three numbers from the user.
- 2Use if-elif-else with combined conditions to find the maximum.
- 3Store the result in a variable named largest.
- 4Print the largest value.