I am a beginner in learning Python and I am currently reading "Learning Python the Hard Way." In one of its exercises, there's a code that says:

def bear_room():

    print "There is a bear here."
    print "The bear has a bunch of honey."
    print "The fat bear is in front of another door."
    print "How are you going to move the bear?"
    bear_moved = False

    while True: 

        next = raw_input("> ")

        if next == "take honey":
            dead("The bear looks at you then slaps your face off.")

        elif next == "taunt bear" and not bear_moved: 
            print "The bear has moved from the door. You can go through it now." 
            bear_moved = True

        elif next == "taunt bear" and bear_moved:
            dead("The bear gets pissed off and chews your leg off.")

        elif next == "open door" and bear_moved:

            print "I got no idea what that means."

I am confused as to what's the use of the while True condition in this code. What is being tested as True? I do understand if it's something like: while x < 9 [do something]. But here, while True means what?

5 Years
Discussion Span
Last Post by vishesh

True never becomes False or similar False-like value so the loop continues until break statement or exception inside loop.


It would run infinitely(until user breaks or exception occurs inside as pyTony said).

The basic syntax for while expression is while <expression> . Every iteration your python interpreter checks if <expression> evaluates to True . If it doesn't the loop ends. Now in case of while True expression is True and evaluates to True, always; hence running forever.

PS> Sorry, just noticed the Solved tag.

Edited by vishesh: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.