Why use "while' here?

This is the place for queries that don't fit in any of the other categories.

Why use "while' here?

Postby DragonDon » Wed May 29, 2013 11:50 am

I am going through Learn Python The Hard Way and in lesson 35 (http://learnpythonthehardway.org/book/ex35.html) there is a use of a "while" that I don't quite understand.

What is exactly being tested as True and where would it change to False?

Code: Select all
    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."
Posts: 2
Joined: Wed May 29, 2013 11:45 am

Re: Why use "while' here?

Postby metulburr » Wed May 29, 2013 12:04 pm

Code: Select all
while True:

is testing boolean value, thus always being True, which is an infinite loop. Although you normally would have a break statement somewhere in the loop being tested each time to test if its time to break out of the loop yet. You could use this method or:
Code: Select all
running = True
while running:
   if some_condition:
      running = False

The only time it exits is when execution of dead() when sys.exit() is called, where it kills the script. However this is not how you want to code programs. You want to have the program run to the end of the script, by breaking out of the loop at some point.
we will be moving to python-forum.io on October 1 2016
more details here
User avatar
Posts: 2244
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Re: Why use "while' here?

Postby DragonDon » Wed May 29, 2013 12:23 pm

Ah, ok. A kind of 'cheap infinite loop' type of deal. Thanks for the response. Would never have found that on Google (although I might now as soon as Google crawls this page :) )
Posts: 2
Joined: Wed May 29, 2013 11:45 am

Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 10 guests