[python] Take a list of numbers and return the average

Doing GCSE computing and as a homework task I need to do the below. I'm only starting out with programming and I've been trying to figure out how to do it but to no avail. I believe I need to use a function but searching "python function list" etc gives me no help when I try it.

Can you just tell me how to:

Ask user to input a "list of numbers"
Print these numbers out for confirmation
Convert them to a variable(s)?
Add them together
Divide sum by number of numbers entered - Not even the slightest clue as to how do that!
Finally, print Average is and the result.

What I've got at current:

print("Welcome, this program will find the average of a list of numbers you enter.")

numbers = input("Enter your numbers, seperated by spaces.")

print("You have entered")

print(numbers)

print(numbers[0])
print(numbers[1])
print(numbers[2])
print(numbers[3])
print(numbers[4])
print(numbers[5])
print(numbers[6])

print(len(numbers))

print("The average of the above numbers is: ") #FURTHEST I'VE GOT

This question is related to python list function average

The answer is


If you have the numpy package:

In [16]: x = [1,2,3,4]    
    ...: import numpy
    ...: numpy.average(x)

Out[16]: 2.5

Simple math..

def average(n):
    result = 0
    for i in n:
      result += i
      ave_num = result / len(n)
    return ave_num

input -> [1,2,3,4,5]
output -> 3.0

The input() function returns a string which may contain a "list of numbers". You should have understood that the numbers[2] operation returns the third element of an iterable. A string is an iterable, but an iterable of characters, which isn't what you want - you want to average the numbers in the input string.

So there are two things you have to do before you can get to the averaging shown by garyprice:

  1. convert the input string into something containing just the number strings (you don't want the spaces between the numbers)
  2. convert each number string into an integer

Hint for step 1: you have to split the input string into non-space substrings.

Step 2 (convert string to integer) should be easy to find with google.

HTH


You want to iterate through the list, sum all the numbers, and then divide the sum by the number of elements in the list. You can use a for loop to accomplish this.

average = 0
sum = 0    
for n in numbers:
    sum = sum + n
average = sum / len(numbers)

The for loop looks at each element in the list, and then adds it to the current sum. You then divide by the length of the list (or the number of elements in the list) to find the average.

I would recommend googling a python reference to find out how to use common programming concepts like loops and conditionals so that you feel comfortable when starting out. There are lots of great resources online that you could look up.

Good luck!


You can use python's built-in function sum

  • sum will return the sum of all the values
  • len to get list's length

code:

>>> list = [1,2,3,4]
>>> sum(list)
>>> 10
>>> len(list)
>>> 4
>>> avg = float(sum(list))/len(list)
>>> 2.5
>>>"""In pyton3 don't want to specify float"""
>>> 10 / 4
>>> 2.5 

Use float because when using python 2.x, because:

  • int/int returns int value (i.e. 2)
  • float/int returns float value (i.e. 2.5)

While in Python 3.x:

  • int/int return float
  • int//int return int

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to function

$http.get(...).success is not a function Function to calculate R2 (R-squared) in R How to Call a Function inside a Render in React/Jsx How does Python return multiple values from a function? Default optional parameter in Swift function How to have multiple conditions for one if statement in python Uncaught TypeError: .indexOf is not a function Proper use of const for defining functions in JavaScript Run php function on button click includes() not working in all browsers

Examples related to average

np.mean() vs np.average() in Python NumPy? Take a list of numbers and return the average How to manipulate arrays. Find the average. Beginner Java Finding moving average from data points in Python Calculating average of an array list? SQL query with avg and group by How to compute the sum and average of elements in an array? Finding the average of a list Trying to get the average of a count resultset Calculating arithmetic mean (one type of average) in Python