do...while loops

Greg Jorgensen gregj at pobox.com
Tue Feb 6 15:25:50 EST 2001


In article <3A802319.46EBCA35 at cybermesa.com>, Jay O'Connor
<joconnor at cybermesa.com> wrote:

> Umm..then how about a counter?  Would this work?
>
> x = 100
> while x:
> 	print x
> 	x -= 1
>
> Yeah, just tried it...it works.
>
> Umm...anyone really like it? :)

That's a common C idiom, but I've always disliked it because x is
either a logical or arithmetic value depending on which statement you
are looking at. I prefer:

  while x > 0:
    ...
    x -= 1

To me this has several advantages:

1. There is absolutely no question about what the loop is doing:
counting down to zero, not waiting for some flag named x to be false.

2. If x is initially negative the loop won't even get started, whereas

  x = -1
  ...
  while x:
    ...
    x -= 1

Will loop for a long time and then crash.

3. The explicit comparison will still work if x is changed from an
integer to a floating point type. This kind of bug is particularly hard
to find:

  x = (((11.0 / 3.0) / 3.0) * 3.0) * 3.0  # 10.999999999999998
  ...
  while x:
      print x
      x -= 1

x will never be exactly equal to 0 because of floating-point
representation and rounding errors. The example above will even print
the sequence 11.0, 10.0, 9.0, ... 1.0, so it may not be immediately
obvious why the loop doesn't terminate.

--
Greg Jorgensen
Portland, Oregon, USA
gregj at pobox.com


Sent via Deja.com
http://www.deja.com/



More information about the Python-list mailing list