Python Can';我的代码不正确
我不明白我做错了什么。当我运行此代码时,它将询问Python Can';我的代码不正确,python,Python,我不明白我做错了什么。当我运行此代码时,它将询问问题。作为原始输入。如果我没有输入任何内容,它会正确地说“这不是一个方向”,并再次提出这个问题。然而,下一次我输入任何东西时,不管我输入什么,都会出现一个空白的答案。为什么它没有持续循环?问题是的“left”。startswith(“”)将返回True。所以,当你第一次不回答时,你就会跳出while循环(因为“left”以“”开头)并转到if/else 在if语句中,lor的值是”,因此您将进入else分支。此时问题会再次被询问,但当用户回答时,新
问题
。作为原始输入。如果我没有输入任何内容,它会正确地说“这不是一个方向”,并再次提出这个问题。然而,下一次我输入任何东西时,不管我输入什么,都会出现一个空白的答案。为什么它没有持续循环?问题是的“left”。startswith(“”)将返回True。所以,当你第一次不回答时,你就会跳出while循环(因为“left”
以“
”开头)并转到if/else
在if语句中,lor
的值是”
,因此您将进入else
分支。此时问题会再次被询问,但当用户回答时,新值lor
将不起任何作用
我建议您编辑while循环,内容如下:
#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()
这样,只有当答案以“left”或“right”开头且不是空字符串时,才能中断while循环
您还应该去掉最后的else
语句,因为它没有做任何有用的事情:)“left”。startswith(lor)
应该是另一种方式:lor.startswith('left')
这同样适用于“right”。从(lor)
开始你可以编辑你的问题,使你的问题更明显吗?(否则,mods可能会关闭您的问题。)“left”。startswith(lor)
应该是另一种方式:lor.startswith('left')
。这样可能也更有意义。此外,我注意到你一直在发布非常类似的问题,在每个问题中你都会说“这是我第一次尝试python”。你确定吗?@blender解决了这个问题!@2rs2ts我实际上已经在我的代码中编写了它,我只是复制/粘贴了整个内容。这和我想纠正的代码是一样的。现在我们只需要@Blender提交一个正式答案,这样Rheanna就可以接受它,这个问题不会永远没有答案与评论中建议的其他解决方案相比,我更喜欢这个解决方案。这可能会允许使用'left'
的任何子字符串作为提示的答案,例如'l'
while lor == "" or (not "left".startswith(lor) and not "right".startswith(lor)):