无法正确使用我的代码

时间:2013-06-11 20:44:58

标签: python

#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。作为raw_input。如果我没有放任何东西,它会正确地说“那不是一个方向”,并且第二次提出这个问题。但是,下次我放入任何内容时,无论我输入什么内容,它都会显示为空白。为什么它不会不断循环?

2 个答案:

答案 0 :(得分:4)

问题是"left".startswith("")将返回True。所以发生的事情是,当你第一次没有回答时,你最终会退出while循环(因为"left"""开头)并转到if / else。

在if语句中,lor的值为"",因此您最终会进入else分叉。此时再次询问问题,但是当用户响应时,lor的新值没有任何作用。

我建议您编辑while循环以阅读:

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

这样,如果答案以“left”或“right”开头并且不是空字符串,则只会中断while循环。

您还应该删除最终的else语句,因为它没有做任何有用的事情:)

答案 1 :(得分:2)

"left".startswith(lor)应该是另一种方式:lor.startswith('left')
"right".startswith(lor)也是如此。