3

我正在用 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循环,但如果我删除“是”或“否”,所以只有答案列表,它会起作用

我该如何处理两个论点?我做错了什么?

4

3 回答 3

1

为什么要像这样声明函数:

def input_checker(prompt, answers):  

#...

并在调用函数时将尽可能多的有效回复列表作为连接列表传递?

pizza = input_checker("Do you like pizza? ", yes + no)
于 2015-05-17T05:01:36.490 回答
1

我相信您所追求的是以下实现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'

@Jorge Torres 是对的;当您声明*answers或在我的示例中将两个列表作为“有效输入”传递时,您的“while 循环”永远不会终止,*valid因为您正在尝试检查是否user_inputs在我的情况下是tuple包含 2 个项目(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
于 2015-05-17T05:05:14.273 回答
1
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:

会回来False,永远不会结束。您可以像这样更改代码

input_checker(prompt, answers):
# ...
pizza = input_checker("Do you like pizza? ", yes + no)
于 2015-05-17T05:14:47.973 回答