while loop-用Python创建一个基于文本的游戏.如何检查用户输入



我正在用Python创建一个基于文本的游戏,需要有关splat参数的帮助。我有一个函数可以测试输入是否有效,还允许您访问库存。我有两个参数,一个用于获取输入提示,另一个是该提示的有效答案。答案是一个splat参数,因为提示可以有多个答案。这个功能是:

def input_checker(prompt, *answers):  
    user_input = raw_input(prompt).lower()
    if user_input == "instructions":
        print
        instructions()
    elif user_input == "i" or user_input == "inventory":
        if len(inventory) == 0:
            print "There is nothing in your inventory."
        else:
            print "Your inventory contains:",  ", ".join(inventory)
    else:
        if user_input in answers:
        return user_input
        else:
            while user_input not in answers:
                user_input = raw_input("I'm sorry.  I did not understand your answer.  Consider rephrasing. " + prompt )
                if user_input in answers:
                    return user_input
                    break

我有两个列表,其中包含问题的常见答案:

yes = ["yes", "y", "yup", "yep"]  
no = ["no", "n", "nope"]

如果我这样调用函数:

pizza = input_checker("Do you like pizza? ", yes, no)

它总是执行while循环,再次要求输入,但如果我删除"是"或"否",所以只有答案列表,它将工作

我该如何进行两次争论?我做错了什么?

为什么要这样声明函数:

def input_checker(prompt, answers):  
#...

并在调用函数时传递与串联列表一样多的有效回复列表?

pizza = input_checker("Do you like pizza? ", yes + no)

我相信您所追求的是userinput():的以下实现

示例:

#!/usr/bin/env python
try:
    input = raw_input
except NameError:
    pass
def userinput(prompt, *valid):
    s = input(prompt).strip().lower()
    while s not in valid:
        s = input(prompt).strip().lower()
    return s

演示:

>>> userinput("Enter [y]es or [n]o: ", "y", "n")
Enter [y]es or [n]o: a
Enter [y]es or [n]o: foo
Enter [y]es or [n]o: y
'y'

@豪尔赫·托雷斯是对的;当您声明*answers或在我的示例中声明*valid时,当传入两个列表作为"有效输入"时,您的"while循环"将永远不会终止,因为在我的例子中,您试图检查user_inputs是否是包含2个项的tuple的成员(2个列表(。

在您的情况下,answers看起来像这样:

answers = (["yes", "y", "yup", "yep"], ["no", "n", "nope"],)

为了说明这一点:

>>> answers = (["yes", "y", "yup", "yep"], ["no", "n", "nope"],)
>>> "yes" in answers
False
>>> "no" in answers
False
def input_checker(prompt, *answers):  
# ...
pizza = input_checker("Do you like pizza? ", yes, no)

所以answers就是元组(["yes", "y", "yup", "yep"], ["no", "n", "nope"])

(如果您呼叫input_checker("Do you like pizza? ", yes, no, ["foo", "bar"]),则answers将是(["yes", "y", "yup", "yep"], ["no", "n", "nope"], ["foo, "bar")(

和循环中的表达式

while user_input not in answers:

将返回CCD_ 13并且永远不会结束。你可以像这个一样更改代码

input_checker(prompt, answers):
# ...
pizza = input_checker("Do you like pizza? ", yes + no)

相关内容

  • 没有找到相关文章

最新更新