Short-circuit Logic
Chris Angelico
rosuav at gmail.com
Thu May 30 13:23:11 EDT 2013
On Fri, May 31, 2013 at 2:58 AM, rusi <rustompmody at gmail.com> wrote:
> On May 30, 5:58 pm, Chris Angelico <ros... at gmail.com> 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
loops over nothing and does not go into an infinite loop (or throw an
exception) when n >= m, you have to at least acknowledge that I'm in
agreement with Python core code here :) That doesn't mean it's right,
of course, but it's at least a viewpoint that someone has seen fit to
enshrine in important core functionality.
ChrisA
More information about the Python-list
mailing list