Home > Net >  How do I take the average (mean) of inputted numbers in Python?
How do I take the average (mean) of inputted numbers in Python?

Time:11-14

I would like to take create a code that takes an input of numbers, and then takes the average (mean) of these numbers. So far, I have this:

from statistics import mean

numbers=int(input("Enter some numbers. Seperate each number by a space: ") 
average=mean(grades)
print(average)

Running this code gives me an error stating "invalid literal for int() with base 10: ' 12 13 14 15 16 17 17'". I have tried to convert the input into a list, but this also failed; I don't know what else to do or try.

CodePudding user response:

Your'e trying to convert the whole input to one int. Get the input string then split it and convert to ints individually.

from statistics import mean

user_input = input("Enter some numbers. Seperate each number by a space: ").strip()

numbers = [int(x) for x in user_input.split(' ')]

average = mean(numbers)

print(average)

CodePudding user response:

numbers=[int(x) for x in input("Enter some numbers. Seperate each 
number by a space: ").split()]
print(numbers)
average=mean(numbers)
print(average)

CodePudding user response:

The idea to convert input into a list was right. Here is one of the ways to do so:

numbers = list(map(int, input().split(" ")))
average = mean(grades)
print(average)

CodePudding user response:

from statistics import mean

numbers = input("Enter some numbers. Separate each number by a space: ")

# After the input numbers is a string that looks like this "1 2 3 4"

# .split(" ") splits the string based on the space. It returns a list of individual items
# strip removes the trailing and leading white spaces
# map applies the first arg (here int) on each element of the second arg (here a list of numbers as strings)
numbers = list(map(int, numbers.strip().split(" ")))

average = mean(numbers)
print(average)
  • Related