Search code examples
pythonpython-3.xnumpymedian

How to find the median?


I am trying to create a function that can get any number of inputs and find the median. I feel like I am going about this all wrong, I cannot get this functional.
What do I need to do?

  1. I made my list
  2. I asked user for inputs
  3. I sorted with numpy
  4. I printed median

Code:

import numpy

numbers = [1,2,3]                
1 = input("Please type your first number")            
2 = input("please type your second number")       
3 = input("please type your third number")       
median = numpy.median(numbers)            
print(median) 

What I am trying to accomplish:

What numbers would you like to find the median for? 1,2,3,4,5,6,7
The median is: 4


Solution

  • You should store the numbers in a list, and use a loop to add numbers to it.

    import numpy
    
    size = int(input("Enter number of numbers you would like to enter"))
    numbers = []
    for i in range(size):
        numbers.append(int(input("Please type in number %d" % i)))
    
    median = numpy.median(numbers)  
    
    print(median) 
    

    Your approach fails because you try to use numbers as variable names, which is not valid.