Short-circuit Logic

Roy Smith roy at panix.com
Thu May 30 08:40:16 EDT 2013


In article <mailman.2395.1369891346.3114.python-list at python.org>,
 Chris Angelico <rosuav at gmail.com> wrote:

> On Thu, May 30, 2013 at 3:10 PM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
> > # Wrong, don't do this!
> > x = 0.1
> > while x != 17.3:
> >     print(x)
> >     x += 0.1
> >
> 
> Actually, I wouldn't do that with integers either. There are too many
> ways that a subsequent edit could get it wrong and go infinite, so I'd
> *always* use an inequality for that:
> 
> x = 1
> while x < 173:
>     print(x)
>     x += 1

There's a big difference between these two.  In the first case, using 
less-than instead of testing for equality, you are protecting against 
known and expected floating point behavior.

In the second case, you're protecting against some vague, unknown, 
speculative future programming botch.  So, what *is* the right behavior 
if somebody were to accidentally drop three zeros into the source code:

> x = 1000
> while x < 173:
>     print(x)
>     x += 1

should the loop just quietly not execute (which is what it will do 
here)?  Will that make your program correct again, or will it simply 
turn this into a difficult to find bug?  If you're really worried about 
that, why not:

> x = 1
> while x != 173:
>     assert < 172
>     print(x)
>     x += 1



More information about the Python-list mailing list