Sunday 3 March 2013

Coding Gold Dust: How to break out from an infinite loop (in Python)

Infinite loops have many uses... In the earlier post I presented a 'Pythonian' way of writing an infinite loop. Obviously in some cases, the loop needs to be 'near infinite' - without the user forcible breaking the execution with Ctrl+C. The simplest way is to use the break command:
while True:
    do_something
    if some_condition:
        break

For example, reading some input from the user ('the oracle answers'):
while True:
    s = raw_input("What's your question?")
    if s == "who are you":
        print "Raspberry Pi!"
    if s == "quit":
        break

Many other programming languages have the break command as well.

But if the body of the while loop grows longer - spanning maybe even more than a 'screenful', it might become not so readable anymore. If there are certain defined exit condition(s), why have a while True declaration at all. Wouldn't it be better to tell the reader of the code that there is going to be something breaking out of the loop? For this we can use an exit variable:
done = False
while not done:
    s = raw_input("What's your question?")
    if s == "who are you":
        print "Raspberry Pi!"
    if s == "quit":
        done = True
...the 'while not done' should read pretty clearly for a human and as not False equals True, the loop runs as long as the variable value is False.

Of course, there might be multiple such loops in a lengthier program and the exit condition might change. So it should make sense to use an exit variable named to tell what is the actual condition - for example when waiting for a GPIO connected hardware button:
button_pressed = False
while not button_pressed:
    # do something
    # do something more
    button_pressed = read_GPIO_button_press()
And so on... Obviously these are no longer that infinite loops, but well, that's how the question was posed originally ;)

No comments:

Post a Comment

Note: only a member of this blog may post a comment.