variable assignment in "while" loop

sismex01 at sismex01 at
Tue Jul 29 17:07:09 CEST 2003

> From: Sybren Stuvel [mailto:sybrenUSE at] 
> Sent: Martes, 29 de Julio de 2003 07:09 a.m.
> 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?
> Sybren

Well, you say you've programmed C since 14, but not how old you
are now, so... you could be programming C for six months if you're
14-and-a-half ;-)

Assignment, in Python, is not an expression, it's a statement;
it doesn't "return" any value, it binds an object's reference
to a name.  Multiple chained assignments in Python don't work
the same way as they do in C, because in Python they're merely
syntactic sugar so you don't have to type them by hand.

Anyhow... the best way to do what you wanna is simply:

while 1:
    info = mydbcursor.fetchone()
    if not info: break
    print "Information:", info

a-ha! you say; yes, the "print" statement ("STATEMENT", not function)
automagically applies str() to the given object, so if you directly
print an object, you don't have to str() it, print does that for

"But it's so cumbersome" you think, looking upon an inconditional-
turned-conditional loop.  Don't worry, it'll become natural with
practice, and after a bit you'll recall your previous C loops
and think "ewww".  Why?  Because, the C compiler is doing
exactly that, only implicitly, and hiding it from you.
That's bad.

You could also:

info = mydbcursor.fetchone()
while info:
    print "Information:", info
    info = mydbcursor.fetchone()

and there's nothing wrong with this; the only "anti-aesthetic"
thing here is the duplicated line which assigns to "info",
but that's small potatos, really; don't worry about that.

Another way, with more modern versions of Python, is to
iterate directly over the cursor:

for info in mydbcursor:
    print "Information:", info

Why?  Because cursors, if I recall correctly, are iterable
objects, so you can iterate through them using for: or any
other similar construct.

Welcome to programming bliss :-)


Advertencia:La informacion contenida en este mensaje es confidencial y
restringida, por lo tanto esta destinada unicamente para el uso de la
persona arriba indicada, se le notifica que esta prohibida la difusion de
este mensaje. Si ha recibido este mensaje por error, o si hay problemas en
la transmision, favor de comunicarse con el remitente. Gracias.

More information about the Python-list mailing list