On Thu, Oct 2, 2008 at 12:06 PM, David <[EMAIL PROTECTED]> wrote: > 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.
This is a common issue beginners to programming have. The question you ask yourself here is " do I really need a direct reference in code to all my values?" It appears to me that you don't. For example, how would you do this in real life? would you say x = num1 x2 = num2 x3 = num3 ... xn = numn x + x2 + x3 + x4 ... + xn / n or would you do this: 1 + 2 + 3 + 4 + 5 / count I would do the latter. It's the same way in programming. You can create these generic collections of items in Python. They are called "lists." I'm a little pressed for time (i have a class starting in a few minutes) but this example should hopefully spark something in 'ya. a = [] b = [1,2,3,4,5] for item in b: a.append(item) Does that give you a hint about how you can add items to a collection without caring how many you have? Note that you can also do something like this (this is a bigger hint) a = [] b = [1,2,3,4,5] for i in range(len(b)): a.append(b[i]) Good luck! > > It would be great if someone could guide me towards the right track!! > > Thanks, > > David > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor