Short-circuit Logic

Chris Angelico rosuav at gmail.com
Thu May 30 01:22:23 EDT 2013


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

Well, in Python I'd use for/range, but the equivalent still applies. A
range() is still based on an inequality:

>>> list(range(1,6))
[1, 2, 3, 4, 5]
>>> list(range(1,6,3))
[1, 4]

Stops once it's no longer less than the end. That's safe, since Python
can't do integer wraparound.

ChrisA



More information about the Python-list mailing list