Newbie question related to Boolean in Python

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Sep 5 22:28:07 EDT 2013


On Thu, 05 Sep 2013 16:36:55 -0700, Thomas Yang wrote:

> 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."
> 	    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."
> 
> # sorry if it looks confusing, this is the real code

No it isn't, because it gives an indent error. The first line is 
unindented, the second line is indented. One of those must be wrong.

py> bear_moved = False
py>     while True:
  File "<stdin>", line 1
    while True:
    ^
IndentationError: unexpected indent


Please be careful of indentation. Python's indentation rules are great 
for code, but not so great for copying and pasting into emails and 
websites. So beware, and take extra care with indentation.

Copied from your previous message, your question was:

> # So what confused me is line 12-13. if my input is taunt bear, is it
> suppose to be taunt bear == "taunt bear" and bear_moved which is true
> and true? which means the loop will continue instead of cancelling it.

The relevant two lines are:

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


I don't understand your question. Nothing cancels the loop anywhere. 
Presumably the loop repeats forever, unless the function dead() contains 
a sys.exit or similar.

The first time around the loop, the bear has not moved, and presumably is 
blocking the door. So the variable `bear_moved` is false. If the user's 
command is "taunt bear" (the poorly named variable `next`) then the first 
time around the loop this if statement will trigger:

    if next == "taunt bear" and not bear_moved:

a message will print stating that the bear moves away from the door, and 
`bear_moved` will be set to True. At that point, the *entire* 
if...elif...else block is finished, execution will jump to the end of the 
loop, and the next loop will begin.

The second time through the loop, the user is prompted for a command 
again. If the user enters "taunt bear" a second time, then 

    if next == "taunt bear" and bear_moved:

is triggered, since this time `bear_moved` is True, and the bear eats the 
character.


Does this answer your question?



-- 
Steven



More information about the Python-list mailing list