Loop-and-a-half (Re: Curious assignment behaviour)
Huaiyu Zhu
huaiyu at gauss.almadan.ibm.com
Thu Oct 11 17:58:35 EDT 2001
On Thu, 11 Oct 2001 13:21:57 +1300, Greg Ewing <greg at cosc.canterbury.ac.nz>
wrote:
>I feel the solution to this is *not* to go in for
>any sort of assignment-in-expressions hackery, but
>to provide a decent loop-and-a-half control structure.
A general "loop-and-half" structure is
A
start loop
B
if C: break
D
end loop
E
Which could be written in the following pattern
A
while B; C:
D
E
Example 1:
> while:
> x = get_next()
> gives x:
> whatever(x)
could be written as
while x = get_next(); x:
whatever(x)
Example 2:
> What if you want to read until you get to a delimiter?
>
> while (line := readline()) != 'end': ...
could be written as
while line = readline(); line != 'end': ...
Example 3:
for (start; do_other, end; incr) do_something;
could be written as
start
while do_other; not end:
do_something
incr
Likewise, a general nested "if-else-and-a-half" structure is like
A
if B:
C
else:
D
if E:
F
else:
G
if H:
I
else:
...
which could be written as
if A; B:
C
elif D; E:
F
elif G; H:
I
else:
...
The advantage of this syntax pattern is that it is flatter than existing
Python syntax, which is a Good Thing <tm>. The disadvantage is that it
cannot handle additional statement after nested 'else', but the existing
'elif' pattern could not do it, either.
Huaiyu
More information about the Python-list
mailing list