Loop-and-a-half (Re: Curious assignment behaviour)

Paul Rubin phr-n2001d at nightsong.com
Sun Oct 14 02:55:28 CEST 2001

news at davidglasser.net (David Glasser) writes:
> > Just today I had a bug that went something like:
> > 
> >     n = compute_number_of_items()
> >     for i in range(n):
> >        try: process_an_item(items[i])
> >        except: break
> >     update_database('number of items processed = ' % i)
> [but for n = 0, i never gets defined]
> I'm confused.  Won't this give the wrong answer, anyway?  If you do
> process all n correctly, i will be set to n-1.  So you'll have to log
> "i+1".  And by this point you might as well just increment a variable
> every time you process an item correctly, which is a lot clearer than
> using the value of a loop index outside of the loop, in my opinion.

In that example it should have said range(1,n+1), I guess.  The actual
code with the bug worked a little bit differently-- the example just
abstracted it, incorrectly it turned out.  (The real code stored the
number of the last item processed, not the number of items processed,
and originally read the number from the database).

More information about the Python-list mailing list