If/then style question

Rob Richardson Rob.Richardson at rad-con.com
Fri Dec 17 09:09:49 EST 2010


-----Original Message-----
What about,


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

---- I reply -----

This is interesting, but I don't understand it (which speaks volumes
about the level of my understanding of Python).

First, just to clarify, I don't think the indentation I saw was what was
originally posted.  The "else" must be indented to match the "if", and
the two statements under "else" are in the else block.  The return
statement is indented at the same level as the for statement, so that it
will be executed after the for loop exits.  Correct?

Now, the for loop will set condition to cond1 and exitCode to 'error1'.
Then it checks the contents of the condition variable.  But what does
"not <variable_name>" by itself mean?  I'm guessing that it checks that
the variable refers to an object.  So, the first time through, condition
refers to cond1, the if condition is false, and the else block gets
executed, and exitCode is changed to refer to good1.  The next time
through the loop, condition is set to refer to cond2 and exitCode is set
to refer to 'very bad error'.  Again, condition is refering to
something, so the else block is executed and we do useful stuff again,
which is probably not helpful and could well be harmful.  exitCode is
set to good1, we're finished with the loop, and we return exitCode.  

What happens if we try to do useful stuff, and we can't?  Where does the
error indication get set?  And once it does get set, the only way we can
exit the for loop is for condition to not refer to anything.  How can
that happen?

Thank you very much for your explanation and your patience with one who
only uses Python in very simplistic ways.

RobR




More information about the Python-list mailing list