0

为这个查询的基本性质道歉 - 这几乎是我的第一个 Python 脚本。

我希望用户输入与扑克牌相对应的两个字符串(例如 2c、3s)并让程序检查两件事:首先,它是否在有效卡片列表中,其次,该卡片是否已经进入。如果任一条件失败,我希望提示用户重新输入卡。我所写的内容会执行这些操作,但不会同时执行这些操作 - 例如,如果卡无效,则会提示用户,但如果重新输入的卡已经在列表中,则不会出现提示。我看不出如何同时测试这两种东西。

无论如何,这就是我所拥有的:

posscards=["ac",
           "2c",
           "3c",
           "4c",
           "5c" #and so on] 


for x in range(0, decksize):
        answer=raw_input("next card? ")
        while answer not in posscards:
            answer = raw_input("not a possible card - try again: ")
        while answer in deck1:
            answer = raw_input ("you've already had that one - try again: ")
        deck1.append(answer)
4

2 回答 2

3

您可以使用具有两个条件while的单个循环来代替两个循环。例如:whileif

prompt = "next card? "
while True:
    answer = raw_input(prompt)
    if answer not in posscards:
        prompt = "not a possible card - try again: "
    elif answer in deck1:
        prompt = "you've already had that one - try again: "
    else:
        deck1.append(answer)
        break

如果你把它分解成一个函数,它可能会更具可读性:

def get_card():
    while True:
        answer = raw_input(prompt)
        if answer not in posscards:
            prompt = "not a possible card - try again: "
        elif answer in deck1:
            prompt = "you've already had that one - try again: "
        else:
            return answer

现在,每次您调用 时get_card,都保证(最终)返回答案。因此,您的主循环可能如下所示:

deck1 = []
for x in range(decksize):
    answer = get_card()
    deck1.append(answer)

你可以把它变成一个单行:

deck1 = [get_card() for x in range(deck size)]
于 2013-11-14T22:34:27.500 回答
0

顺便说一句,我在任何地方都看不到deck1。确保在尝试向其附加内容之前声明。

deck1 = []

while answer not in posscards and answer in deck1:
     answer = raw_input("not a possible card or card already entered- try again: ")
于 2013-11-14T22:26:22.797 回答