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:
            gold_room()

        else:
            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?

Recommended Answers

All 2 Replies

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

Member Avatar for GreenDay2001

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.