Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 274
Lesley Hawkes Avatar asked Nov 30 '25 11:11

Lesley Hawkes


1 Answers

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
like image 87
Mohammed Yasin Avatar answered Dec 03 '25 00:12

Mohammed Yasin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!