473,762 Members | 6,675 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Assignment in a while?

Hi all,

First, let me preface this by the fact that I'm completely new to the
language, but not to programming in general.

I'm trying to get my feet wet with something near and dear to my heart:
database programming. Here's what I've got:

import pgdb;

dbh = pgdb.connect(da tabase = 'test')
sth = dbh.cursor()
sth.execute("SE LECT * 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.

Thanks in advance,
Ben
Apr 2 '06 #1
9 3505
none/Ben wrote:

Assignment within a while loop seems like a pretty standard thing, so I'm just
curious what I'm missing.


The FAQ on this subject? ;-)

http://www.python.org/doc/faq/genera...-an-expression

It's "standard" in C-flavoured languages, certainly, but probably not
ubiquitous.

Paul

Apr 2 '06 #2
So it seems that I stumbled on the idiomatic way of doing this then.
Well, as they say, "When in Rome..." :). Thanks for pointing out the
FAQ. I'll be reading up on it.

Cheers,
Ben

Paul Boddie wrote:
none/Ben wrote:
Assignment within a while loop seems like a pretty standard thing, so I'm just
curious what I'm missing.

The FAQ on this subject? ;-)

http://www.python.org/doc/faq/genera...-an-expression

It's "standard" in C-flavoured languages, certainly, but probably not
ubiquitous.

Paul


Apr 2 '06 #3
none wrote:
import pgdb;

dbh = pgdb.connect(da tabase = 'test')
sth = dbh.cursor()
sth.execute("SE LECT * 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.

Apr 2 '06 #4
Ant
There are various ways you could do this:

If the number of results won't be too big:

....
for result in sth.fetchall():
print result

If it may be very large:
....

result = sth.fetchone()
while result:
print result
result = sth.fetchone()

Or perhaps nicer:

....
def result_iterator (result_set):
yield result_set.fetc hone()

for result in result_iterator (sth):
print result

HTH.

Apr 2 '06 #5
none wrote:
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.


Not much, you cannot assign to a variable in the controlling expression
of a while loop. However, for loops do assign values to variables, so if
the form with the break offends you, try restructuring your code as a for
loop. For example:

for results in iter(sth.fetcho ne, None):
print results

or in many cases you can just fetch everything in one go:

for results in sth.fetchall():
print results
Apr 2 '06 #6
"none <"@bag.python.o rg> wrote:
So it seems that I stumbled on the idiomatic way of doing this then.
Well, as they say, "When in Rome..." :). Thanks for pointing out the
FAQ. I'll be reading up on it.


the idiomatic way to loop in Python is to use iterators/generators. if
you have a callable that fetches data from some resource and returns
a "sentinel" when you get to the end, you can use the iter function to
turn it into an iterator:
help(iter)

Help on built-in function iter in module __builtin__:

iter(...)
iter(collection ) -> iterator
iter(callable, sentinel) -> iterator

Get an iterator from an object. In the first form, the argument must
supply its own iterator, or be a sequence.
In the second form, the callable is called until it returns the sentinel.

given this, your loop can be written:

for result in iter(std.fetcho ne, None):
print result

</F>

Apr 2 '06 #7
Ant
Forget the last suggestion - I wasn't concentrating :-)

Apr 2 '06 #8
none <""thulben\"@(n one)"> wrote:
...
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.


I see you've already received many excellent suggestions, and just
wanted to point out the way in which you CAN "assign-and-test" in those
rare occasions where you really want to (in my experience, that boils
down to: I need Python code whose structure is as close as possible to
some other's language -- either because I need to transliterate into
Python some published "reference implementation" kind of algorithm, or
because I know I'm just doing a _prototype_ in Python, and once that's
accepted some poor folks will have to transliterate it into C or
whatever). Anyway, it boils down to something like...:

class ValueHolder(obj ect):
def __init__(self, value=None):
self.set(value)
def set(self, value):
self.value = value
return value
data = ValueHolder()

and then, say, something like...:

while data.set(zip.zo p()):
frobnicate(data .value)

Not as Pythonic as iterators etc, but structurally very close to

while (xx=zip.zop()) {
frobnicate(xx);
}

if that's what you need to stick close to!-)
Alex
Apr 2 '06 #9
The inline iterator version fits very well with my sensibilities. The
problem that I have with fetchall is that sometimes you need to deal
with a very large dataset. Calling fetchall() on it will put the whole
thing in memory, which is no good. Better to iterate over it one row at
a time, IMO.

Thanks a ton!
Ben

Duncan Booth wrote:
none wrote:

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.

Not much, you cannot assign to a variable in the controlling expression
of a while loop. However, for loops do assign values to variables, so if
the form with the break offends you, try restructuring your code as a for
loop. For example:

for results in iter(sth.fetcho ne, None):
print results

or in many cases you can just fetch everything in one go:

for results in sth.fetchall():
print results

Apr 3 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
3022
by: news | last post by:
I'm trying out the Zend Development Environment 4, and for the most part I like it, except for two things. It seems to think certain lines that are perfectly valid are bugs. Like this: while ($row_pass = mysql_fetch_array($result_pass)) { It gives an "Assignment in Condition" error whenever it encounters a line like that, which is a lot. It gives a little explanation box
6
12216
by: Sybren Stuvel | last post by:
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)
23
3234
by: Paul Rubin | last post by:
OK, I want to scan a file for lines matching a certain regexp. I'd like to use an assignment expression, like for line in file: if (g := re.match(pat, line)): croggle(g.group(1)) Since there are no assignment expressions in Python, I have to use a temp var. That's a little more messy, but bearable:
5
4833
by: CoolPint | last post by:
It seems to me that I cannot assign objects of a class which has a constant data member since the data member cannot be changed once the constructor calls are completed. Is this the way it is meant to be? Am I not suppose not to have any constant data member if I am going to have the assignment operator working for the class? Or am I missing something here and there is something I need to learn about? Clear, easy to understand...
16
2617
by: Edward Diener | last post by:
Is there a way to override the default processing of the assignment operator for one's own __value types ? I realize I can program my own Assign method, and provide that for end-users of my class, but I would like to use internally my own = operator for some of my value types, so I can say "x = y;" rather than "x.Assign(y);". The op_Assign operator seems impossibly broken since it takes __value copies of the two objects. Perhaps there is...
3
311
by: ccwork | last post by:
>There are two assignments here. In one assignment, p is modified. The >prior value of p is arguably used to determine the new value stored into >p, as you explained, but it is _also_ read to determine at which memory >location the second assignment will happen, so it is not _only_ read to >determine the value stored, therefore undefined behavior. There is something wrong. The first assignment is "p->next = q" and
77
4750
by: berns | last post by:
Hi All, A coworker and I have been debating the 'correct' expectation of evaluation for the phrase a = b = c. Two different versions of GCC ended up compiling this as b = c; a = b and the other ended up compiling it as a = c; b = c. (Both with no optimizations enabled). How did we notice you may ask? Well, in our case 'b' was a memory mapped register that only has a select number of writable bits. He claims it has been a 'C...
35
2454
by: nagy | last post by:
I do the following. First create lists x,y,z. Then add an element to x using the augumented assignment operator. This causes all the other lists to be changed also. But if I use the assignment x=x+ instead of using the augumented assignment, the y and z lists do not change. Why is that? This does not happen when I work with integer data type for example, as shown below. Thanks for your help
16
7332
by: Johannes Bauer | last post by:
Hello group, I'm just starting with Python and am extremely unexperienced with it so far. Having a strong C/C++ background, I wish to do something like if (q = getchar()) { printf("%d\n", q); } or translated to Python:
0
9554
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9377
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8814
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7358
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5266
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5405
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3913
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3509
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2788
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.