[Tutor] for/else question
Jeff Shannon
jeff at ccvcorp.com
Thu Sep 11 19:06:23 EDT 2003
Gabriel Cooper wrote:
> Secondly, isn't
> breaking out of a loop considered "bad programming"? Much like GOTO's?
Actually, no it's not. Indeed, one of the recommended idioms in
Python (to replace the do ... while loop of some other languages) is:
while 1:
do_stuff()
if (condition):
break
The normal 'while (condition)' loop performs an action 0 or more
times, while the loop above performs an action 1 or more times. This
prevents you from needing to initialize variables (say, reading from a
file to determine the condition) before the while loop and then again
inside of the while loop.
> So... yeah... Do /you/ use "else" with for loops? If so, when?
I seem to recall a discussion of this on comp.lang.python some time
ago, which intimated that it was included as much for symmetry (with
if/else) as for practical need. (The implementation of code suites is
such that it is essentially free -- 'else' works the same whether it
follows a 'for' or an 'if'.)
That said, I can see cases where it's important to know whether you've
broken out of a loop or not. You might need to take an action only if
there are no errors in your loop, for instance. You could use a
sentinel variable, but it's cleaner to avoid that, and for/else allows
you to avoid it.
Jeff Shannon
Technician/Programmer
Credit International
More information about the Tutor
mailing list