My task is to make a Program that finds the median, mode and mean of a user defined number set. I believe that part is done, however it is also suppose to return a "0" if the list is empty. The way i am deriving my number list is through
enterNumbers = list(map(int,input("Enter Numbers : ").strip().split(' ')))[:]
This returns ValueError: invalid literal for int() with base 10: ''
Obviously this will only accept integers as an argument but I don't know where to begin to remedy this.
Full code as follows:
#Define median , Mode and Mean
def median(enterNumbers):
enterNumbers.sort()
middle = len(enterNumbers) // 2
if len(enterNumbers) % 2 == 1:
return enterNumbers[middle]
else:
return enterNumbers[middle] enterNumbers[middle - 1] / 2
def mode(enterNumbers):
numberDictionary = {}
for digit in enterNumbers:
number = numberDictionary.get(digit, None)
if number == None:
numberDictionary[digit] = 1
else:
numberDictionary[digit] = number 1
maxValue = max(numberDictionary.values())
modeList = []
for key in numberDictionary:
if numberDictionary[key] == maxValue:
modeList.append(key)
return modeList
def mean(enterNumbers):
mean = 0
for num in enterNumbers:
mean = num
return mean / len(enterNumbers)
#Define Main Function
def main():
enterNumbers = list(map(int,input("Enter Numbers : ").strip().split(' ')))[:]
enterNumbers.sort()
print("\n"," Number List ","\n---------------------","\n",enterNumbers)
print("\n","median, mode mean?","\n---------------------")
answer = input()
if answer == "median":
answer = median
elif answer == "mode":
answer = mode
elif answer == "mean":
answer = mean
print(answer(enterNumbers))
main()
CodePudding user response:
I would highly recommend to refactor your code. But that would fix your error.
enterNumbers = list(map(int, (input("Enter Numbers : ") or "0").strip().split(' ')))[:]
CodePudding user response:
You can just use a 'Try Except' in this part of your code. Will treat errors in general, even if the user types a String.
def main():
try:
enterNumbers = list(map(int, input("Enter Numbers : ").strip().split(' ')))[:]
enterNumbers.sort()
print("\n", " Number List ", "\n---------------------", "\n", enterNumbers)
print("\n", "median, mode mean?", "\n---------------------")
answer = input()
if answer == "median":
answer = median
elif answer == "mode":
answer = mode
elif answer == "mean":
answer = mean
print(answer(enterNumbers))
except:
print(0)