Loop with Else Clause
Christman, Roger Graydon
dvl at psu.edu
Tue Feb 5 17:28:29 EST 2019
From: Python-list <python-list-bounces+gronicus=sga.ninja at python.org> On
Behalf Of DL Neil
Sent: Monday, February 4, 2019 11:29 PM
To: 'Python' <python-list at python.org>
Subject: Loop with else clause
What is the pythonic way to handle the situation where if a condition exists the loop should be executed, but if it does not something else should be done?
Just reading this by itself without seeing the illustrative problem, my first gut reaction was "while loop!" but then it became more obvious that this was a one-off condition to decide to get started, as opposed to being the loop condition itself.
That being said, I would agree that you really cannot do better than the if-else already presented, since it is clearly a binary choice: execute the complete loop, or don't if you can't.
I personally try to avoid the else part on both while loops and for loops because of this sort of confusion. All other things being equal, having an else section is fundamentally the same thing as simply omitting the 'else:' and out-denting the consequence, and makes it very clear just what is going on.
The difference, of course, appears when you have a 'break' within that loop that exits prematurely. And that's where the structured-programming purist in me starts to gibber in fear and loathing. My purist self says that if 'break' is applicable, than exception handling is just as applicable with a much cleaner model, since you can control where to go next, whether to continue repeating, etc.
If I don't expect to get all the way through a for loop, I simply don't write a for loop -- I'll substitute with a while, moving the logical negation of the break condition into the while loop condition, making it very clear that I don't plan to make it to the end. Unfortunately, the for loop is such a common Pythonic thing to do that I really can't say 'for/break' is unPythonic -- I can only substitute Lovecraftian adjectives (in my opinion, of course) to describe that construct.
But this whole little tangent of mine doesn't seem to apply to your situation at all,
and I don't there is a 'single' language element in any programming language I can think
of that does what you ask -- so stick with the cleaner: if (__): # loop; else: #don't loop
Pennsylvania State University
More information about the Python-list