having problems with a multi-conditional while statement
Ned Deily
nad at acm.org
Tue Jan 6 19:42:26 EST 2009
In article
<40a44d6b-c638-464d-b166-ef66496a0676 at l16g2000yqo.googlegroups.com>,
"bowman.joseph at gmail.com" <bowman.joseph at gmail.com> wrote:
> Hi,
>
> I'm trying to write a multi-conditional while statement, and am having
> problems. I've broken it down to this simple demo.
>
> #!/usr/bin/python2.5
>
> condition1 = False
> condition2 = False
>
> while not condition1 and not condition2:
> print 'conditions met'
> if condition1:
> condition2 = True
> condition1 = True
>
>
> As I understand it, this should print 'conditions met' twice, however,
> it only prints it once. It seems that once condition1 is made true,
> the whole thing evaluates as true and stops the while loop.
Are you perhaps expecting that the "while" condition is tested at the
end of the loop? It's not; it is tested at the top of the loop, so,
once the condition evaluates as false, the loop exits. This can even
result in zero trips:
>>> while False:
... print "never"
...
>>>
Unwinding the snippet above:
>>> condition1 = False
>>> condition2 = False
>>> not condition1 and not condition2
True
>>> if condition1:
... condition2 = True
...
>>> condition1 = True
>>> not condition1 and not condition2
False
# -> while loop exits after 1 trip
--
Ned Deily,
nad at acm.org
More information about the Python-list
mailing list