[Tutor] while and for
Daniel Yoo
dyoo@hkn.eecs.berkeley.edu
Mon, 9 Oct 2000 16:32:24 -0700 (PDT)
On Mon, 9 Oct 2000 CMNOLEN@aol.com wrote:
> I asked earlier for guidance in writing a program to total input from
> 100 entries. It worked great. Now I want the program to contain an
> 'Enter 0 to quit' line. Also I would like a running count of the
> entries to show in the 'The sum is now' line. I am stuck. I guess
> these questions are so basic most print doesn't answer them?I am
> stuck!
What I find helpful is pretend that everything works perfectly, and see
what I expect to see during a sample run. For me, doing this helps me see
what details I'm forgetting, or what I really want the program to do.
Let's try it for your program.
# program begins
Please enter your next number: 1
The sum is now 1 = 1
Please enter your next number: 2
The sum is now 1+2 = 3
Please enter your next number: 42
The sum is now 1+2+42 = 45
Please enter your next number: 0
Goodbye!
# program ends
If we want our program to behave this way, we'll want to keep a "running
sum" string as well as a running total. It would look something like
this:
sumstring = ''
num = input('Please enter your next number: ')
while (we're not done yet): # <-- This needs to be defined somehow
sumstring = sumstring + num + '+'
# ... other stuff
num = input('Please enter your next number: ')
As you can see, as we continue going through the loop, our sumstring will
keep track of all the numbers we've ever seen. It'll grow like this:
'' --> '1+' --> '1+2+' --> '1+2+42+'
So when you print out that sumstring, you'll probably want to chop off the
trailing plus sign.
Now that I look back at your question, I might be completely
misunderstanding what you mean by 'running count'. *grin* If so, sorry
about that! Could you clarify?