1
#this is my very first python attempt

name = raw_input("What is your name?")

if len("string") > 0:
    print "Hello %s, Let's be friends!" % name
else:
    print "Sorry, what was that?"

print ""
print name + ","
lor = raw_input("You come to a crossroads, left or right?")

if lor == "left":
    print "You went left"
elif lor == "right":
    print "You went right"
else:
    print "That's not a direction."

This is my first code. Is there a way to make a person choose right or left again if they wrote in something other than right or left? (so basically take them back to the raw_input of lor)?

4

2 回答 2

2

使用while循环:

query = "You come to a crossroads, left or right?" 
lor = raw_input(query).strip().lower()
while lor not in ("left", "right"):
    print "That's not a direction."
    lor = raw_input(query).strip().lower()

if lor == "left":
    print "You went left"
else:
    print "You went right"

正如其他人在评论中指出的那样,if顶部的条件应该是:if name.

name = raw_input("What is your name?")
if name:
    print "Hello %s, Let's be friends!" % name
else:
    print "Sorry, what was that?"
于 2013-06-11T19:36:10.187 回答
2

这是@Ashwini Chaudhary 的回答,略有改动。

question = "You come to a crossroads.  Go left or right?"
lor = raw_input(question)
while not "left".startswith(lor) and not "right".startswith(lor):
    print "That's not a direction."
    lor = raw_input(question)

if "left".startswith(lor):
    print "You went left"
else:
    print "You went right"

此更改允许用户键入少于整个单词的内容。用户可以通过键入“l”、“le”、“lef”或“left”来向左移动。类似地,用户可以通过键入“r”、“ri”、“rig”等来向右移动。

此外,由于问题被重复,我创建了一个变量并两次使用了该变量。这样,如果您更改问题,您只需要在一个地方更改它。

您可以编写一个函数,该函数接受一个问题和该问题的有效答案列表,然后在循环中一遍又一遍地询问问题,直到给出有效答案。然后该函数将返回有效答案。此外,即使用户输入了缩写,问题也总是可以返回完整的答案。这是执行此操作的代码:

def ask(question, lst_answers):
    if not question.endswith(' '):
        question += ' '

    while True:
        answer = raw_input(question).strip().lower()
        lst = [a for a in lst_answers if a.startswith(answer)]
        if len(lst) == 1:
            return lst[0]
        else:
            print "Please answer with one of: " + ' '.join(lst_answers)

answer = ask("You come to a crossroads.  Go left or right?", ["left", "right"])
if answer == "left":
    print "You went left"
else:
    print "You went right"

这可能看起来很棘手,但实际上这是一种懒惰的方法。我们在一个地方解决了基本问题,然后你的代码就可以调用这个函数并依靠它来做正确的事情。

ask()函数的核心是“列表推导”,我们在其中列出与表达式匹配的所有答案。表达式是a.startswith(answer),因此我们得到一个新列表,其中包含以用户键入的内容开头的所有答案。然后我们检查我们是否得到了一个答案。如果我们得到零答案,则用户输入了一些奇怪的东西。如果我们得到多个答案,则用户输入了一个简短的缩写,但匹配了多个单词:例如,如果我们接受“left”或“look”的答案,而用户只输入了“l”。如果我们只得到一个答案,我们就会返回那个答案,很高兴这是完整的答案,而不是用户输入的缩写!

于 2013-06-11T19:45:10.543 回答