while (assignment):

John Roth newsgroups at jhrothjr.com
Wed Jul 30 03:12:21 CEST 2003


"Sybren Stuvel" <sybrenUSE at YOURthirdtower.imagination.com> wrote in message
news:slrnbicopb.6gh.sybrenUSE at sybren.thirdtower.com...
> Hi there,
>
> Is it possible to use an assignment in a while-loop? I'd like to do
> something like "loop while there is still something to be read, and if
> there is, put it in this variable". I've been a C programmer since I
> was 14, so a construct like:
>
> while info = mydbcursor.fetchone():
> print "Information: "+str(info)
>
> comes to mind. Unfortunately, this doesn't work. Is there a similar
> construct in python?

For most purposes, there is. Just use a for loop!
As long as the source behaves like an iterator, the for
loop will automatically assign each result.

Something like this:

   for info in mydbcursor.resultset:
        print "Information: " + str(info)

In this, mydbcursor.resultset has to look like
a sequence of some kind (list or tuple),
or be an iterator. Since what you presumably
have is a result set from a data base query,
that's a rather natural fit. You might have to wrap
the result set to make it an iterator, but I'd think
any good db package would catch up eventually.

HTH
John Roth
>
> Sybren
> -- 
> The problem with the world is stupidity. Not saying there should be a
> capital punishment for stupidity, but why don't we just take the
> safety labels off of everything and let the problem solve itself?






More information about the Python-list mailing list