我的密码没法用

2024-06-14 02:53:48 发布

您现在位置: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。作为原始输入。如果我不加任何东西,它会正确地说“那不是一个方向”,并再次提出这个问题。然而,下一次我输入任何东西时,不管我输入什么,答案都是空白的。为什么它不不断循环?你知道吗


Tags: thenamerightyouinputyourgetraw
2条回答

问题是"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语句,因为它没有做任何有用的事情:)

"left".startswith(lor)应该是另一种方式:lor.startswith('left')
这同样适用于"right".startswith(lor)。你知道吗

相关问题 更多 >