What does "while True" mean in Python?

Viewed 531972
def play_game(word_list):
    hand = deal_hand(HAND_SIZE) # random init
    while True:
        cmd = raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ')
        if cmd == 'n':
            hand = deal_hand(HAND_SIZE)
            play_hand(hand.copy(), word_list)
            print
        elif cmd == 'r':
            play_hand(hand.copy(), word_list)
            print
        elif cmd == 'e':
            break
        else:
            print "Invalid command."

While WHAT is True?

I reckon saying 'while true' is shorthand, but for what? While the variable 'hand' is being assigned a value? And what if the variable 'hand' is not being assigned a value?

17 Answers

While most of these answers are correct to varying degrees, none of them are as succinct as I would like.

Put simply, using while True: is just a way of running a loop that will continue to run until you explicitly break out of it using break or return. Since True will always evaluate to True, you have to force the loop to end when you want it to.

while True:
    # do stuff

    if some_condition:
        break

    # do more stuff - code here WILL NOT execute when `if some_condition:` evaluates to True

While normally a loop would be set to run until the while condition is false, or it reaches a predefined end point:

do_next = True

while do_next:

    # do stuff

    if some_condition:
        do_next = False

    # do more stuff - code here WILL execute even when `if some_condition:` evaluates to True

Those two code chunks effectively do the same thing

If the condition your loop evaluates against is possibly a value not directly in your control, such as a user input value, then validating the data and explicitly breaking out of the loop is usually necessary, so you'd want to do it with either method.

The while True format is more pythonic since you know that break is breaking the loop at that exact point, whereas do_next = False could do more stuff before the next evaluation of do_next.

While True means loop will run infinitely is no condition is mentioned inside the while loop that breaks it.

You can break the code using 'break' or 'return'

>>> a = ['foo', 'bar', 'baz']
>>> while True:
...     if not a:
...         break
...     print(a.pop(-1))
...
baz
bar
foo

Code copied from the realpython.com

Related