Short-circuit Logic

Rick Johnson rantingrickjohnson at gmail.com
Thu May 30 20:13:25 EDT 2013


> On Fri, May 31, 2013 at 2:58 AM, rusi wrote:
> > On May 30, 5:58 pm, Chris Angelico wrote:
> > > The alternative would be an infinite number of iterations, which is far far worse.
> >
> > There was one heavyweight among programming teachers -- E.W. Dijkstra
> > -- who had some rather extreme views on this.
> > 
> > He taught that when writing a loop of the form
> >
> > i = 0
> > while i < n:
> >   some code
> >   i += 1
> >
> > one should write the loop test as i != n rather than i <
> > n, precisely because if i got erroneously initialized to
> > some value greater than n, (and thereby broke the loop
> > invariant), it would loop infinitely rather than stop
> > with a wrong result.
> > 
> 
> And do you agree or disagree with him? :) I disagree with
> Dijkstra on a number of points, and this might be one of
> them. When you consider that the obvious Pythonic version
> of that code:
> 
> for i in range(n,m):
>     some code

Maybe from your limited view point. What if you need to perform operations on a sequence (more than once) in a non-linear fashion? What if you need to modify the sequence whilst looping? In many cases your simplistic "for loop" will fail miserably. 

py> lst = range(5)
py> for n in lst:
...     print lst.pop()
4
3
2

Oops, can't do that with a for loop!

py> lst = range(5)
py> while len(lst):
...     print lst.pop()
4
3
2
1
0



More information about the Python-list mailing list