Program:
def medianValue(list1):
#Sorting the list
list1.sort()
#Checking the last index
indexes = len(list1)
if(indexes%2 == 0):
#if the number of elements is even, then we have to find average of two middle values
num1 = (indexes) // 2 #first middle element
num2 = (indexes // 2) + 1 #second middle element
#Calculating median as average of the two
med = (list1[num1 - 1] + list1[num2 - 1]) / 2
return med
else:
#if number of elements is odd, then we have to return the element at middle index
middle = (indexes - 1) // 2
med = list1[middle]
return med
#defining empty list
list1 = list()
#Getting input of number of elements to be added in the list
inp = int(input("How many elements do you want to add in the list? "))
#Getting the input of elements from user
for i in range(inp):
a = int(input("Enter the elements: "))
list1.append(a)
#Printing the list
print("The median value is",medianValue(list1))
OUTPUT:
How many elements do you want to add in the list? 6
Enter the elements: 1
Enter the elements: 2
Enter the elements: 3
Enter the elements: 4
Enter the elements: 5
Enter the elements: 6
The median value is 3.5