for / while else doesn't make sense
lawrencedo99 at gmail.com
Sat Jun 4 23:29:19 EDT 2016
On Saturday, June 4, 2016 at 11:37:18 PM UTC+12, Ned Batchelder wrote:
> On Friday, June 3, 2016 at 11:43:33 PM UTC-4, Lawrence D’Oliveiro wrote:
> > On Saturday, June 4, 2016 at 3:00:36 PM UTC+12, Steven D'Aprano wrote:
> > > You can exit a loop because you have run out of items to process, or you can
> > > exit the loop because a certain condition has been met.
> > But why should they be expressed differently?
> > item_iter = iter(items)
> > while True :
> > item = next(item_iter, None)
> > if item == None :
> > break
> > if is_what_i_want(item) :
> > break
> > #end while
> Do you actually write loops like this?
Is that a non-trolling question? Yes. All the time.
> If this appeared in a code review, first we'd have a conversation about
> what this code was meant to do ...
I would hope not.
> ...and then I would ask, "Why aren't you using a for loop?"
... and then I would ask, “Didn’t you read my previous postings where I pointed out the issues with them?”
Here <https://en.wikibooks.org/wiki/Python_Programming/Databases> is another example: see the section “Looping on Field Breaks”. A while-True scales gracefully to complex situations like that. I much prefer universal, adaptable constructs, rather than having to remember different solutions for special cases.
> I suspect most Python programmers would be similarly confused about
> why you aren't using one of the central constructs of the language.
When a language has good and bad parts, it behooves the wise programmer to concentrate on the good parts and try to ignore the bad.
Python’s for-loops have their uses—I *did* point this out too, did you not notice?—but they are best confined to the situations that they are good at.
> What's next? "Why have both if and while? A goto will work for both!"
Passive-aggression aside, funny you should mention that. I use a goto-free structured-programming style in my C code, as exemplified here <https://github.com/ldo/dvd_menu_animator/blob/master/spuhelper.c>. I find it reduces problems with forgetting to free memory, or freeing it twice.
More information about the Python-list