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:For example, reading some input from the user ('the oracle answers'):Many other programming languages have the break command as well.
while True: do_something if some_condition: break
while True: s = raw_input("What's your question?") if s == "who are you": print "Raspberry Pi!" if s == "quit": break
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:...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.
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
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:And so on... Obviously these are no longer that infinite loops, but well, that's how the question was posed originally ;)
button_pressed = False while not button_pressed: # do something # do something more button_pressed = read_GPIO_button_press()