2013-06-11 38 views
-1
#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。如果我没有放入任何东西,它会正确地说“这不是一个方向”,并且再次提出这个问题。但是,下次我输入任何内容时,无论输入什么内容,它都会作为答案空白。为什么它不连续循环?不能得到我的代码

+1

你能编辑你的问题,以便你所问的更明显吗? (否则,mods可能会关闭你的问题。) – 2rs2ts

+5

'“left”.startswith(lor)'应该是相反的方法:'lor.startswith('left')'。这也许更有意义。 – Blender

+2

另外,我注意到你一直在发布非常类似的问题,在每个问题中你都会说“这是我第一次尝试Python”。你确定*吗? – 2rs2ts

回答

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)): 

这样,你只跳出while循环,如果答案为“左”或“右”开始,而不是空字符串。

你也应该摆脱最终else声明的,因为它不会做任何有用的:)

+1

我喜欢这个解决方案比评论中提出的更好。据推测,这将允许任何“左”的子字符串被用作对提示的回答,例如, ''L'' –

2

"left".startswith(lor)应该是周围的其他方法:lor.startswith('left')
这同样适用于"right".startswith(lor)

相关问题