Find Median Value
Find the median of three values without sorting a list. A Python exercise on two possible orderings, compound conditions, and handling equal middle values.
1# Take three numbers2a = float(input("Enter first number: "))3b = float(input("Enter second number: "))4c = float(input("Enter third number: "))56# Find median7if (a >= b and a <= c) or (a <= b and a >= c):8 median = a9elif (b >= a and b <= c) or (b <= a and b >= c):10 median = b11else:12 median = c1314print(f"Median: {median}")
Output
Enter first number: 10 Enter second number: 5 Enter third number: 15 Median: 10.0
In this one
- Define a median
- Check both possible orderings
- Preserve equal values
How it works
- 1
Read three floats.
- 2
Test whether a lies between the others, then b.
- 3
Otherwise select c and print median.
Edge cases
What is the median of 2, 2, 9?
What is the median of 2, 2, 9?
2; duplicates still occupy positions in the ordered data.
Is this the arithmetic mean?
Is this the arithmetic mean?
No. It selects the middle value rather than adding and dividing.
What's going on
The median of three values is the middle one when ordered. a qualifies if it lies between b and c in either direction, which explains the two groups joined by or.
If a is not between them, the next test tries b. Otherwise c must be the middle value. Inclusive comparisons keep equal values valid. The sample 10, 5, 15 chooses 10.0, not the average of the three.
What is the median of 2, 2, 9? 2; duplicates still occupy positions in the ordered data.
Is this the arithmetic mean? No. It selects the middle value rather than adding and dividing.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why check two arrangements for a?
Pick an answer to check it.
Question 2
What is the median of 2, 2, 9?
Pick an answer to check it.
Questions people ask
What is the median of 2, 2, 9?
2; duplicates still occupy positions in the ordered data.
Is this the arithmetic mean?
No. It selects the middle value rather than adding and dividing.
Why check two arrangements for a?
Either b or c may be the smaller neighbor.
๐Related Content
- ๐
Phase 1 - Learn Concepts
Review Phase 1 concepts and explanations
- ๐
Phase 1 - Quiz
Test your Phase 1 understanding with quiz questions
- ๐ป
Phase 1 - All Practice Problems
Explore all practice problems for Phase 1
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum