2013-11-14 50 views
0

這個查詢的基本性質的道歉 - 這幾乎是我的第一個Python腳本。Python - 檢查兩個同時條件的raw_input字符串?

我希望用戶輸入一個對應一張紙牌的雙字符字符串(例如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) 
+0

作爲一個側面說明,你可能想要寫一些代碼來生成'明信片「列表,而不是手動寫出來。然後你只需要寫13 + 4的值而不是13 * 4,並且你可以把這13個值寫成13個字符的字符串。例如,'posscards = [value +'適合''cshd'適合'a23456789tjqk'中的值]'即使你不理解嵌套列表理解(你可能不這樣做),你應該可以寫它是一個4行'for'的陳述。 – abarnert

回答

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