If/then style question

Rob Richardson Rob.Richardson at rad-con.com
Fri Dec 17 11:06:30 EST 2010


My thanks for pointing out the existence of the else: suite in the for
statement.  However, I remain confused.  For reference, here's the
original code:

> def myMethod():
>     for condition, exitCode in [
>             (cond1, 'error1'),
>             (cond2, 'very bad error'),
>     ]:
>         if not condition:
>             break
>     else:
>        do_some_usefull_stuff() # executed only if the we never hit the

> break statement.
>        exitCode = good1
>
>     return exitCode

What do we know about cond1 and cond2?  Do they have to be assigned
before this for statement is executed?  The sample code doesn't show it.


The loop is going to to execute once for condition = cond1 and exitCode
= 'error1'.  The only thing it's going to do is check to see what
condition is.  Since we can assume (I hope) that cond1 is not false,
then the for loop continues.  Now condition = cond2 and exitCode = 'very
bad error'.  The if condition is still false, so the loop continues.
We've come to the end now, and the else: suite is executed.  We finally
do some useful stuff and exitCode = good1.  (Should that have been in
quotes, or doesn't it matter?)  But now the for loop's job is done and
we return the exitCode, which at this point is good1.  

But I still don't understand what happens if we can't do useful stuff.
Where does an error code get set, and where is that error code checked?
We don't have a chance to check it in the for loop, because once we're
in the else: suite the loop condition is never rechecked.  Or is it?

Thanks again!

RobR



More information about the Python-list mailing list