a basic question about "while true"


level: beginner

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)
        elif cmd == 'r':
            play_hand(hand.copy(), word_list)
        elif cmd == 'e':
            print "Invalid command."

my question: 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?

9/20/2010 7:08:29 PM

while True means loop forever. The while statement takes an expression and executes the loop body while the expression evaluates to (boolean) "true". True always evaluates to boolean "true" and thus executes the loop body indefinitely. It's an idiom that you'll just get used to eventually! Most languages you're likely to encounter have equivalent idioms.

Note that most languages usually have some mechanism for breaking out of the loop early. In the case of Python it's the break statement in the cmd == 'e' case of the sample in your question.

9/20/2010 7:14:20 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow