Wednesday, January 25, 2012

Python Patterns: Non-Empty Strings are True

The idiomatic way in Python of writing a non-terminating while-loop is:
    while 1:
or the (slightly slower) alternative:
    while True:
I saw a suggestion on the Python mailing list that I really like, which relies on the behaviour that non-empty strings are evaluated by conditions to be True and provides a self-documented truth-condition, which can note why the loop is non-terminating or what the break condition is.
    while "the program is running":

    while "data is still streaming":

    while "no one presses escape":

1 comment: