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

Steve Holden sholden at holdenweb.com
Fri Oct 12 20:09:56 EDT 2001


"Jyrinx" <jyrinx at mindspring dot com> wrote ...
> Erm, I'm hardly a seasoned hacker, but if I may toss in a few cents ...
>
> > |     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)
>
[ summary of prior discussion ]
>
> I like Python's for loop, "range()" idiom and all. In any case, I should
> think the above code would be clearer anyway with an explicit check for an
> empty list:
>
>     n = compute_number_of_items()
>     if n == 0:
>         update_database('no items processed')
>    else:
>         for i in range(n):
>            try: process_an_item(items[i])
>            except: break
>         update_database('number of items processed = ' % i) # (Hmm? I
> thought the % operator was supposed to be used with a string and a
> dictionary? Not that # I would know what I'm talking about ... :-)
>
The left-hand operand is always a string. If it only contains one format
item, the right-hand operand can either be a simple data item or a
one-element tuple (confusingly referred to as a "singleton" in the Python
documentation). If the format items in the string have parenthesised names
in them then the right-hand operand is expected to be a mapping (i.e. to
have a __getattr__() method), and the parenthesised portions are passed as
attribute names to __getattr__().

> Or, if you didn't want to make an extra branch and didn't want the
> uninitialized-i problem, why not just initialize it to 0 before the loop?
>
Slightly bug-prone, but not a bad solution.

regards
 Steve
--
http://www.holdenweb.com/






More information about the Python-list mailing list