Python IF THEN chain equivalence
Diez B. Roggisch
deets at nospam.web.de
Thu Nov 13 17:11:12 EST 2008
jzakiya schrieb:
> I'm translating a program in Python that has this IF Then chain
>
>
> IF x1 < limit: --- do a ---
> IF x2 < limit: --- do b ---
> IF x3 < limit: --- do c ---
> .-----
> ------
> IF x10 < limt: --- do j ---
> THEN
> THEN
> -----
> THEN
> THEN
> THEN
>
> In other words, as long as 'xi' is less than 'limit' keep going
> down the chain, and when 'xi' isn't less than 'limit' jump to end of
> chain a continue.
>
> Is this the equivalence in Python?
>
> IF x1 < limit:
> --- do a ---
> elif x2 < limit:
> --- do b ---
> ----
> ----
> elif x10 < limit:
> --- do j ---
Of course not. After "do a", it would stop.
You need to use
if x1 < limit:
do a
if x2 < limit:
do b
...
Alternatively, and depending on the nature of "do X", you can do
for x, todo in ((x1, do_a), (x2, do_b), ...):
if x < limit:
todo()
else:
break
This implies though that the "dos" are pure functions without (variable)
arguments.
Diez
More information about the Python-list
mailing list