Python - 检查两个同时条件的raw_input字符串?

时间:2013-11-14 22:22:30

标签: python python-2.7

对此查询的基本性质表示歉意 - 这几乎是我的第一个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)

2 个答案:

答案 0 :(得分:3)

您可以使用具有两个while条件的单个while循环,而不是两个if循环。例如:

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

答案 1 :(得分:0)

顺便说一下,我没有'在任何地方看到dekk1'。确保在尝试向其附加内容之前声明。

deck1 = []

while answer not in posscards and answer in deck1:
     answer = raw_input("not a possible card or card already entered- try again: ")