Luis Colon
Luis Colon

Reputation: 27

How to calculate average / mean on python 2.7

Im trying to calculate the average when an user will enter the numbers and will stop when he decide. I manage to get the sum however I cant divided it because I need somehow get the quantity of the inputs before he stops entering. Here is my code so far:

print (" please enter all the numbers you want to calculate the avarage. After you enter all of them press 'f' to finish.")

s = 0

x = raw_input ('please enter the number')

while (num != 'f'):
    x = eval (x)
    s = s + x
    x = raw_input ('please enter the number')

print (' the average is'), s

Like you see I manage to get the sum however I dont know how I can get the quantity of the input to then divide the sum with this to get the average. Any help will be appreciated

Upvotes: 0

Views: 1441

Answers (1)

logic
logic

Reputation: 1727

You just needed to add a counter inside your while loop:

print (" please enter all the numbers you want to calculate the avarage. After you enter all of them press 'f' to finish.")

s = i = 0         #declare counter: i = 0

x = raw_input ('please enter the number')

while (x != 'f'):
    x = eval (x)
    s = s + x
    i+=1          #increment counter: i=i+1 or i+=1 (these 2 options are equivalent)
    x = raw_input ('please enter the number')

print (' the average is'), s/i    #divide the sum by counter

Upvotes: 1

Related Questions