Question

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

Was it helpful?

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.

OTHER TIPS

You cannot assign values to 1, 2, or 3. Additionally, you need to convert the strings from input to ints. Try some simple changes.

import numpy                
input1 = input("Please type your first number")            
input2 = input("Please type your second number")       
input3 = input("Please type your third number")
numbers = map(int, [input1, input2, input3])
median = numpy.median(numbers)            
print(median) 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top