[Tutor] dealing with user input whose value I don't know

David ldl08 at gmx.net
Thu Oct 2 19:06:29 CEST 2008


Hello,

I am trying to do some exercises in John Zelle's book (chapter 4).
I got stuck:

"Write a program that finds the average of a series of numbers entered 
by the user. The program should first ask the user how many numbers 
there are. Note: the average should always be a float, even if the user 
inputs are all ints."

Okay, I can ask how many number are to be added:

numbers = input("How many number do you want me to calculate? ")

If I then get a reply, say "5", what I would have to do next is to ask 
for the five numbers so that I can calculate the average.
But given that I don't know the the value of 'numbers' ex ante, how 
could I ask for the right amount of numbers?
I don't see how this can be achieved with the tools I have learned so far...
I am currently thinking along the lines of

ans1, ans2 = input("Enter the numbers separated by a comma: ")
average = (ans1 + ans2) / 2.0

But as I say - I don't know how many assignment there have to be, nor do 
I know how Python could then create these assignments.

It would be great if someone could guide me towards the right track!!

Thanks,

David


More information about the Tutor mailing list