954,510 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

When to use a "while True:" condition?

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 thewhile 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?

piethon
Newbie Poster
1 post since Jul 2011
Reputation Points: 10
Solved Threads: 0
 

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

pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

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.

vishesh
Nearly a Posting Virtuoso
1,381 posts since Oct 2006
Reputation Points: 85
Solved Threads: 42
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You