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

christopher.henk at allisontransmission.com christopher.henk at allisontransmission.com
Thu Oct 2 19:22:50 CEST 2008


tutor-bounces+christopher.henk=allisontransmission.com at python.org wrote on 
10/02/2008 01:06:29 PM:

> 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? ")

        you should really use raw_input to get the info from the user, and 
then convert it to a number.
        numbers=int(raw_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.

        Write the code like you knew it was going to be a 5 and then 
replace anywhere the 5 appears with the variable 'numbers'.



> 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...

        Looking at the table of contents it looks like you should have 
learned about loops by now.



> I am currently thinking along the lines of
> 
> ans1, ans2 = input("Enter the numbers separated by a comma: ")
> average = (ans1 + ans2) / 2.0

        have each number be its own input and repeat it depending on how 
their input for numbers, and then do the averaging at the end.

> 
> 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.
> 
        you don't need to keep the individual numbers only the sum, but if 
you want to, use a list and append each new number to the end of the list.

> It would be great if someone could guide me towards the right track!!
> 
> Thanks,
> 
> David
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20081002/5151b259/attachment-0001.htm>


More information about the Tutor mailing list