Joseph Yeagle
Joseph Yeagle

Reputation: 13

Not getting the average

count = 0
total = 0
while True:

    inp = raw_input ('enter a number:')
    if inp == 'done' : break
    if len(inp) < 1 : break


    num = float(inp)
    count = count + 1
    total = total + num
    print num, total, count

print "average:", total/count

My print out is not showing the average, Am I missing something?

Upvotes: 0

Views: 84

Answers (4)

jez
jez

Reputation: 15349

I expect you're forgetting to enter the string done once you've finished feeding it numbers. Alternatively you can just press return, giving it an empty input. As written, the code is only designed to give you the average after you've done one of those two things.

If you want it to show the running average after each input, indent the last line of code (the one that prints the average) so that it's part of the loop.

Upvotes: 0

robbawebba
robbawebba

Reputation: 349

Your code is working properly. Don't forget to enter done into the prompt when you are done collecting data to display the average! If you would like to display the average each time you enter a new number, just move the average print statement inside the while True loop and keep it at the end.

Upvotes: 0

Lost Robot
Lost Robot

Reputation: 1321

Works in Python 2.

enter a number: 5
5.0 5.0 1
enter a number: 9
9.0 14.0 2
enter a number: 7
7.0 21.0 3
enter a number: 0
0.0 21.0 4
enter a number: done
average: 5.25

You can also use numpy.mean.

Upvotes: 1

prenc
prenc

Reputation: 151

Works in python 3.5

count = 0
total = 0
while True:
    inp=input('enter a number:')
    if inp == 'done' : break
    if len(inp) < 1 : break


    num = float(inp)
    count = count + 1
    total = total + num
    print (num, total, count)

print ("average:", total/count)

Upvotes: 0

Related Questions