-2

I have the following code to prompt entries and to calculate a median. It works fine for an odd number of entries, but for even entries when it needs to take the average of 2 middle numbers I get a type error.

import statistics
x=input("How many numbers do you want to enter? ")
x=int(x)
tup=()
for i in range(0,x):
    y=input("Enter number ")
    tup+= (y,)
print("Median= ",statistics.median(tup))

How can I fix this?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
blinds0r
  • 13
  • 2
  • 3
    Instead of us entering numbers, can you change this to an example that has canned input and include expected output? – tdelaney Mar 08 '20 at 22:28
  • Wouldn't it have been faster to read the error message? – Kelly Bundy Mar 08 '20 at 22:29
  • Which version of python? Are you using version 2.7? – tdelaney Mar 08 '20 at 22:30
  • @HeapOverflow - Odd numbers shouldn't work either in python 3 because `input` returns a string. That's why I asked. – tdelaney Mar 08 '20 at 22:33
  • @HeapOverflow - okay, that's bizzare. `statistics.median(("1", "2", "10"))` works but `statistics.median(("1", "2", "10", "20"))` doesn't, unsupported operand types. So there's the problem! – tdelaney Mar 08 '20 at 22:36
  • @HeapOverflow - True, I was focused on the error part. Anyway, the duplicate link is clearly not the answer to this problem so I've voted to reopen. Renaud has the right answer. – tdelaney Mar 08 '20 at 22:39
  • @tdelaney the question is edited to have the solution so it should either be closed or edited... – Tomerikoo Mar 08 '20 at 22:41
  • @Tomerikoo -the edit is good, but OP should accept one of the answers to close it that way. – tdelaney Mar 08 '20 at 22:43
  • @blinds0r if you solved your own problem, feel free to answer your own question and even accept it. But don't edit the solution inside the question, kinda loses the point of having a question in the first place... – Tomerikoo Mar 08 '20 at 22:45

2 Answers2

3

You need to convert str that you get from input to numbers (int or float):

import statistics
x=input("How many numbers do you want to enter? ")
x=int(x)
tup=()
for i in range(0,x):
    y=input("Enter number ")
    tup+= (float(y),)  # convert str to float
print("Median= ",statistics.median(tup))
AGN Gazer
  • 8,025
  • 2
  • 27
  • 45
1

Is your error isn't due to you dont cast y as int, and I'm not sure it's possible to manipulate tuple as you wish. I think you better use list:

import statistics
x=input("How many numbers do you want to enter? ")
x=int(x)
list=[] 
for i in range(0,x):
    y=input("Enter number ")
    y=int(y)
    list.append(y)
print("Median= ",statistics.median(list))
Renaud
  • 2,709
  • 2
  • 9
  • 24