Reading Time: 1 minutes
Median of Three Values in Python: A Python program to calculate median of three values.
Median of Three Values in Python
# MEDIAN OF THREE VALUES # A program to calculate median of three values. The program should contain two functions; one for computing the median; the other a main program that reads 3 numbers and displays the median # The median value is the middle of the three values when they are sorted into ascending order. # Input: 3 numbers # Output: median of the three numbers # Also, ensure that your file when imported into another file doesn't trigger your program automatically # THOUGHT PROCESS: Devise two functions: one for computing the median of three supplied numbers and returning the median; second the main function to take three numbers as input, pass them to the median calculating function, and then display the returned median. def medianOf(num1, num2, num3): if num1 < num2 < num3 or num3 < num2 < num1: return num2 if num1 < num3 < num2 or num2 < num3 < num1: return num3 else: return num1 def mainProgram(): number1 = int(input("Enter first number: ")) number2 = int(input("Enter second number: ")) number3 = int(input("Enter third number: ")) median = medianOf(number1, number2, number3) print("Median of", str(number1), str(number2), str(number3), "is:", median) # if the file has been run directly AND not been imported, call the main function if __name__ == "__main__": mainProgram()
Try it here. You will have to call mainProgram() function yourself, since we have made the script independent by adding the if construct.