[Tutor] dealing with user input whose value I don't know
steve at alchemy.com
Thu Oct 2 19:12:38 CEST 2008
On Fri, Oct 03, 2008 at 01:06:29AM +0800, David wrote:
> I am trying to do some exercises in John Zelle's book (chapter 4).
> I got stuck:
> 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?
You don't need to know in advance what the value of <numbers>
will be. You can have Python iterate <number> times, asking
for an additional number each time.
You could add each to a variable (so it accumulates the sum
as you iterate) and then divide by <number>. You could collect
everything in a list and then do the calculation.
There's a couple of ideas. See where that leads you and let
Steve Willoughby | Using billion-dollar satellites
steve at alchemy.com | to hunt for Tupperware.
More information about the Tutor