Wednesday, October 19, 2011

Python’s for/else

Ned Batchelder:

As the loop executes, the “if” becomes like a giant if/elif/elif ladder: each time around the loop adds another test of the condition, but only if all previous tests were false. The “else” clause caps it all off, just as it would in an explicit if/elif/else structure. And it works just like the explicit structure: if all of the conditions are false, then the “else” clause is run.

Even though I understand the problem this is trying to solve, I have never found it intuitive. I still have to think when reading or writing one of these loops. It just doesn’t seem worth it for such a small gain.

Comments RSS · Twitter

Leave a Comment