-2
#this is my very first python attempt
#Getting the name
print ""
name = raw_input("Hello, adventurer. Before we get started, why don't you tell me your name.")
while name in (""):
    print "Sorry, I didn't get that."
    name = raw_input("What is your name?")

if len(name) > 0:
    print ""
    print "%s? Good name! I hope you are ready to start your adventure!" % name

#getting right or left
print ""
print "Well %s, we are going to head north along the river, so get a move on!" % name
print ""
question = "As you head out, you quickly come across a fork in the road.  One path goes right, the other goes left. Which do you chose: right or left?"
lor = raw_input(question).strip().lower()
while not "left".startswith(lor) and not "right".startswith(lor):
    print "That's not a direction."
    lor = raw_input(question).strip().lower()

if len(lor) > 0:
    if "left".startswith(lor):
        print "You went left"
    elif "right".startswith(lor):
        print "You went right"
else:
    print "That's not a direction."
    lor = raw_input(question).strip().lower()

我不明白我做错了什么。当我运行此代码时,它会询问question。作为原始输入。如果我没有输入任何内容,它会正确地说“这不是一个方向”,并再次提出问题。但是,下次我输入任何内容时,无论我输入什么,它都会作为答案出现空白。为什么它不连续循环?

4

2 回答 2

4

The problem is that "left".startswith("") will return True. So what's happening is that when you don't answer the first time, you end up breaking out of the while loop (because "left" starts with "") and going to the if/else.

At the if statement, the value of lor is "" so you end up in the else fork. At that point the question gets asked again, but when the user responds, nothing is done with the new value of lor.

I would recommend editing your while loop to read:

while lor == "" or (not "left".startswith(lor) and not "right".startswith(lor)):

This way you only break out of the while loop if the answer starts with "left" or "right" and is NOT the empty string.

You should also get rid of the final else statement because it doesn't do anything useful :)

于 2013-06-11T20:58:16.773 回答
2

"left".startswith(lor)应该反过来lor.startswith('left')
"right".startswith(lor).

于 2013-06-11T21:01:44.473 回答