Assignment in a while?
bill pursell
bill.pursell at gmail.com
Sun Apr 2 15:15:36 EDT 2006
none wrote:
> import pgdb;
>
> dbh = pgdb.connect(database = 'test')
> sth = dbh.cursor()
> sth.execute("SELECT * FROM capitals")
> #while 1:
> #results = sth.fetchone()
> #if results == None:
> #break
> #print results
> while results = sth.fetchone():
> print results
>
> If I try to run the above code, I get a SyntaxError indicating that I
> can't do an assignment in the while loop. I found a way around this
> (see the commented out while loop), but it seems hackish. Assignment
> within a while loop seems like a pretty standard thing, so I'm just
> curious what I'm missing.
A more pythonic way to do that is something like:
for results in sth.fetchall():
print results
(I'm not familiar with pgdb, but if it's a reasonable module it will
have some function that returns an iterator.)
In the beginning of my python experience, I was a bit irritated at
being unable to assign and check a condition in one statement, but the
irritation really doesn't last very long. Python has a huge amount of
inherent beauty, and is well worth the time.
More information about the Python-list
mailing list