tags:

views:

123

answers:

2

Is while True an accepted method for looping over a block of code until an accepted case is reached as below? Is there a more elegant way to do this?

while True:
    value = input()
    if value == condition:
        break
    else:
        pass
# Continue code here.

Thank you for any input.

+7  A: 

That's the way to do this in Python. You don't need the else: pass bit though.

Note, that in python 2.x you're likely to want raw_input rather than input.

SilentGhost
Thank you, I am using 3.1.1 and the else is purely a place holder, my code is a little more than the above :-). I have used this syntax for a while and just occured to me that it may be that another technique is more widely accepted.
Thorsley
@Thorsley: that's absolutely fine.
SilentGhost
While 1: is also common (1 is always true)
Zonda333
@Zonda: `>>> isinstance(True, int) --> True`
SilentGhost
`True` is more idiomatic and I believe more widely preferred.
Wayne Werner
A: 

If it's deterministic, then yes. If it is not deterministic (thus meaning you could be stuck in a loop forever at some statistical likelihood) then no.

If you wanted to make it a little more clean and easier to debug as the code grows larger, use a boolean or integer to indicate the status of your loop condition.

San Jacinto