replacing 'else' with 'then' in 'for' and 'try'

ROGER GRAYDON CHRISTMAN dvl at psu.edu
Mon Nov 6 10:37:17 EST 2017


Just a little two-cent opinion from the peanut gallery:


I've been following all the discussion on this go by, sometimes getting

a bit heated at times, and just sitting nice and safe and secure in my

little ivory tower, where I simply tell my students to not use 'break'.


As a stodgy educator, I usually restrict them for these two reasons:

1) the loop condition should describe your expected loop conditions, and

2) the exception handling structure allows more control over where

     the exceptional circumstances will be handled (including which function)


When it comes to searching an iterable collection, my ivory-tower

view point tells me that the looping condition is based on whether the

item is found, and is not a for loop traversing the entirety.    

To me, that is the 'one obvious way to do it'


If I expect the item will be found, but fear that it will not, I can always
compare

a subscript to len(), or if that seems too hard, catch the StopIteration
exception.

I only recommend the for loop when the true expectation is to visit

the entire collection (which can later be moderated with iter's sentinel

parameter, or some of the filters in itertools)


And I see that simply removing 'break' from my vocabulary, this

whole 'else on a loop' issue completely dissolves.


So thank you for, even unintentionally, helping me to feel good

about living inside my ivory tower!


Roger Christman

Pennsylvania State University



More information about the Python-list mailing list