w3resource

Python Exercise: Find the median of three values


40. Median of Three Values

Write a Python program to find the median of three values.

Pictorial Presentation:

Python Exercise: Find the median of three values

Sample Solution:

Python Code:

# Prompt the user to input the first number and convert it to a floating-point number, assigning it to the variable 'a'
a = float(input("Input first number: "))

# Prompt the user to input the second number and convert it to a floating-point number, assigning it to the variable 'b'
b = float(input("Input second number: "))

# Prompt the user to input the third number and convert it to a floating-point number, assigning it to the variable 'c'
c = float(input("Input third number: "))

# Determine the median among the three numbers

# Check if 'a' is greater than 'b'
if a > b:
    # Check if 'a' is less than 'c'
    if a < c:
        median = a
    # Check if 'b' is greater than 'c'
    elif b > c:
        median = b
    else:
        median = c
# If 'a' is not greater than 'b'
else:
    # Check if 'a' is greater than 'c'
    if a > c:
        median = a
    # Check if 'b' is less than 'c'
    elif b < c:
        median = b
    else:
        median = c

# Display the calculated median among the three input numbers
print("The median is", median)

Sample Output:

Input first number: 25                                                                                        
Input second number: 55                                                                                       
Input third number: 65                                                                                        
The median is 55.0 

Flowchart :

Flowchart: Find the median of three values

For more Practice: Solve these Related Problems:

  • Write a Python program to calculate the median of three numbers using conditional statements.
  • Write a Python program to sort three input numbers and return the middle element as the median.
  • Write a Python program to compute the median of three numbers without using built-in sorting functions.
  • Write a Python program to implement a function that returns the median of three given values using pairwise comparisons.

Go to:


Previous: Write a Python program to display the sign of the Chinese Zodiac for given year in which you were born.
Next: Write a Python program to get next day of a given date.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.