[Tutor] still confused about for loops
Brian van den Broek
brian.van.den.broek at gmail.com
Wed Dec 19 19:06:04 CET 2012
On 19 December 2012 01:19, Brandon Merritt <merrittb7 at gmail.com> wrote:
> Sorry, I am just so confused and aggravated as to why this won't work - why
> doesn't it print out the whole list? :
>
> number = raw_input('Enter a 7-unit number: ')
>
> for i in number:
> count = []
> count.append(i)
>
> print count
>
>>>> Enter a 7-unit number: 78953298
> ['8']
>
> --
> Brandon Merritt
> (707) 481-1744
Brandon,
Others have pointed out the problem here and in your counter thread.
I have a bit of meta-advice that will help you to resolve these sorts
of problems on your own.
When confronted by a small chunk of code that is not behaving as you
expect, it can help to grab a pen and paper and interpret the code by
hand, going through it and updating the various data values as you run
through the program step by step. Often, this will force you to see
the point at which your mental model of what you have written diverges
from what you have actually written.
Less work, and often sufficient to expose the problem is to put in
some print statements.
Had you tried:
for i in number:
count = []
count.append(i)
print count
I suspect the problem would have become much more clear.
If I am doing print statement debugging where I've multiple print
statements exposing the same data structure, I will often tag them
like so
for i in number:
print count, 11111111111111
count = []
count.append(i)
print count, 222222222222
That helps figure out just where each printed instance of count came
from. In the case at hand, this version would almost certainly have
sorted you out; the first print will fail with a NameError, and this
might have suggested to you that you have to define count before the
loop.
HTH,
Brian vdB
More information about the Tutor
mailing list