tags:

views:

255

answers:

11

Which one is the pythonic way of below two expressions.

1. while 1:
2. while True:

edit:Is there a pythonic way out of two above expressions?

+1  A: 

I think this is mostly a matter of style. Both should be easily understandable as an infinite loop.

However, personally I prefer the second option. That's because it just takes a mental micro-step less to understand, especially for programmers without C background.

Eli Bendersky
+2  A: 

The first one will work also in those early versions where True is not yet defined.

flybywire
At this point, once you program for Python 3, maintaining backwards compatibility is pretty much moot anyways.
Xorlev
I wonder which was the last version of Python where True wasn't supported?
Eli Bendersky
A: 

This is only a matter of style, any programming beginner will understand either option.

But the second option will only work if True wasn't assigned to False, which was possible until Python 3:

>>> True = False
>>> True
False
AndiDog
That's a good observation, but anyone who does this on a project with other devs will almost certainly be beaten to within an inch of their life...
Justin Ethier
Yes, of course this is only used as joke.
AndiDog
+2  A: 

IMO the second option is more obvious.

If you could get rid of the while and write more compact code, that might be more pythonic.
For example:

# Get the even numbers in the range 1..10
# Version 1
l = []
n = 1
while 1:
    if n % 2 == 0: l.append(n)
    n += 1
    if n > 10: break
print l

# Version 2
print [i for i in range(1, 11) if i % 2 == 0]

# Version 3
print range(2, 11, 2)
Nick D
+2  A: 

If you have an algorithm that is suppose to terminate in a finite time, I would recommend this, which is always safer than while True:

maxiter = 1000
for i in xrange(maxiter):
   # your code
   # on success:
     break
else:
   # that algorithm has not finished in maxiter steps! do something accordingly
Olivier
+4  A: 

The most pythonic way will always be the most readable. Use while True:

For C programmers the most readable is while 1: .
Andrei Ciobanu
"while 1:" is quite different from "for(;;)" :-)
sharjeel
@nomemory: The question was about "Pythonic" -- which has little or nothing to do with C programmers. If you want something readable for C programmers, please use C.
S.Lott
@S.Lott : what I was trying to say is that readability is something very relative.
Andrei Ciobanu
+1  A: 

I believe the second expression is more explicit, and thus more pythonic.

mctylr
+3  A: 
balpha
But in your code, you just have to scan the code for `found_answer = True`.
Mike Graham
I don't see how this is preferable. Often the reason for using a `break` is that the stop condition can't be easily or efficiently expressed. If you literally mean use a variable like `found_answer` then you have to scan for that rather than `break` - and in general you'll still need a `continue` instead of the `break` to make it exit the loop.
Scott Griffiths
@Mike Graham: Yes, and I said I like to avoid this at all. If I use it, I try to make things clear (i.e. readable) by giving the boolean a name that explains *what* it is that makes this loop stop.
balpha
@Scott Griffiths: But unlike `True`, `not found_answer` or `not received_quit_command` tells something to the reader of the code.
balpha
@balpha: That's a fair point, but I can't help feeling that you're introducing a new variable and adding an extra conditional evaluation just to make the intent of the loop clearer, when all you really need is a simple comment at the start?
Scott Griffiths
@Scott Griffiths: ... and at the break statement(s). But yes, that might be a matter of taste; I like to use function and variable names as "comments" where I can; but your point is valid. My point, still, is **either way, try to do something entirely different**. I really fail to understand why this isn't clear from my answer.
balpha
A: 

The better way is "while True" with a conditional break out of the loop.

Jesse Kempf
+10  A: 

Fundamentally it doesn't matter, such minutiae doesn't really affect whether something is 'pythonic' or not.

If you're interested in trivia however, there are some differences.

  1. The builtin boolean type didn't exist till Python 2.3 so code that was intended to run on ancient versions tends to use the while 1: form. You'll see it in the standard library, for instance.

  2. The True and False builtins are not reserved words prior to Python 3 so could be assigned to, changing their value. This helps with the case above because code could do True = 1 for backwards compatibility, but means that the name True needs to be looked up in the globals dictionary every time it is used.

  3. Because of the above restriction, the bytecode the two versions compile to is different in Python 2 as there's an optimisation for constant integers that it can't use for True. Because Python can tell when compiling the 1 that it's always non-zero, it removes the conditional jump and doesn't load the constant at all:

    >>> import dis
    >>> def while_1():
    ...     while 1:
    ...         pass
    ...
    >>> def while_true():
    ...     while True:
    ...         pass
    ...
    >>> dis.dis(while_1)
      2           0 SETUP_LOOP               5 (to 8)
    
    
      3     >>    3 JUMP_ABSOLUTE            3
                  6 POP_TOP
                  7 POP_BLOCK
            >>    8 LOAD_CONST               0 (None)
                 11 RETURN_VALUE
    >>> dis.dis(while_true)
      2           0 SETUP_LOOP              12 (to 15)
            >>    3 LOAD_GLOBAL              0 (True)
                  6 JUMP_IF_FALSE            4 (to 13)
                  9 POP_TOP
    
    
      3          10 JUMP_ABSOLUTE            3
            >>   13 POP_TOP
                 14 POP_BLOCK
            >>   15 LOAD_CONST               0 (None)
                 18 RETURN_VALUE
    

So, while True: is a little easier to read, and while 1: is a bit kinder to old versions of Python. As you're unlikely to need to run on Python 2.2 these days or need to worry about the bytecode count of your loops, the former is marginally preferable.

gz
+1: Excellent explanation for why the question should be downvoted below zero.
S.Lott
I would like to point out that, *in my humble opinion*, the most pythonic way of doing something is to NOT fret about details like this. While the post is absolutely interesting and informative, and I do appreciate that, I stand by the claim that `while True:` is more pythonic. At least the way I interpret the odd term *pythonic*, your mileage may vary.
+2  A: 

It doesn't really matter. Neither is hard to read or understand, though personally I'd always use while True, which is a bit more explicit.

More generally, a whole lot of while–break loops people write in Python could be something else. Sometimes I see people write i = 0; while True: i += 1 ..., which can be replaced with for i in itertools.count() and people writing while True: foo = fun() if foo is None: break when this can be written for foo in iter(fun, None), which requires learning but has less boilerplate and opportunity for silly mistakes.

Mike Graham