0

Hi I am creating a function to compute the mean from a list of integers inputed by the user. I am getting an error:

ValueError: invalid literal for int() with base 10:

Here is my code:

def calcmean (mylist):
    listsum= 0
    for index in mylist:
        listsum = listsum + index
    mean= listsum / len(mylist)
    return mean

userinput= [int(input("Enter list separated by commas:"))]
print (mean (userinput))
001
  • 13,291
  • 5
  • 35
  • 66
ztif
  • 19
  • 2
  • hi, perhaps parse the input string into a list of ints? https://stackoverflow.com/questions/3477502/pythonic-method-to-parse-a-string-of-comma-separated-integers-into-a-list-of-i – jspcal Oct 26 '21 at 15:22
  • You never split the string into comma-separated values. `calcmean` is simply iterating over your input character by character, not number by number. – chepner Oct 26 '21 at 15:32

2 Answers2

0

This should work:

userinput = [int(x) for x in input("Enter list separated by commas:\n").split(', ')]
  • 2
    You can simply split on `','`. `int` itself ignores leading and trailing whitespace in its argument, so `', '` simply makes it more likely you'll pass something bad like `1,2` to `int`. – chepner Oct 26 '21 at 15:33
0

How do you make sure the user will type that numbers totally correct as you expected? What happens if the user types two/three/four/... consecutive commas like 1,2,3,,4,,,,5? It should be handled much more than that. To be clear, you should divide your program to 3 phases, including:

  • Input
  • Process the input
  • Calculate mean.

Following gives you an example:

Input

userinput = input("Please type number separated by commas")

Process the input

# split numbers to items by commas. 
num_array = userinput.split(",")

# chose items that are valid numbers 
def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False 
num_array = [int(item) for item in num_array if is_number(item)]

Calculate mean

As you done in your code

print(mean(num_array))
TaQuangTu
  • 2,155
  • 2
  • 16
  • 30