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
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:
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 valueslen
to get list's lengthcode:
>>> 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 floatint//int
return intSource: Stackoverflow.com