2017-10-19 111 views
0

我試圖用Python編程21點牌遊戲。 在玩家類中,我想定義一個循環,要求玩家決定是「打」還是「站」(二十一點規則)。除非輸入是正確的(無論是「S」還是「H」),循環需要循環,直到玩家輸入其中一個選項。錯誤處理所需的輸入

這是我爲這個特定的部分代碼:

while True: 
    try: 
     D = input('What is your decision, stand or hit? [press S for stand and H for hit]: ') 
     if D in ['S', 'H'] is False: 
      1/0 
    except: 
     print('Incorrect input, please try again (S for stand and H for hit)!') 
     continue 
    else: 
     if D == 'S': 
      print('OK, you decided to stand!') 
     else: 
      print('OK, you decided to hit. You will receive a 3rd card!') 
     break 

這樣的想法是,除非決策是正確的(「S」或「H」),將創建一個錯誤,但到目前爲止,代碼無法正常工作呢...我認爲有一個小毛刺......

任何建議? 親切的問候,

大號

+0

你知道嗎,例如['S','H']中的'Foo'是False'評估結果?它可能讓你感到驚訝。 – jonrsharpe

+0

除了以外,你還期待什麼?你應該期待嘗試除塊 –

回答

1

你應該寫:

if D not in ['S', 'H']: 

而且整個代碼會更短,更易讀沒有例外:

while True: 
    D = input('What is your decision, stand or hit? [press S for stand and H for hit]: ') 
    if D not in ['S', 'H']: 
     print('Incorrect input, please try again (S for stand and H for hit)!') 
     continue 
    else: 
     if D == 'S': 
      print('OK, you decided to stand!') 
     else: 
      print('OK, you decided to hit. You will receive a 3rd card!') 
     break 
1

沒有必要的例外,你可以這樣做:

while True: # infinite loop 
    D = input('What is your decision, stand or hit? [press S for stand and H for hit]: ') 
    if D == "S": 
     #do some 
     break 
    elif D == "H": 
     # Hit some. 
     break 
    else: 
     print('Incorrect input, please try again (S for stand and H for hit)!') 
     break 
+0

謝謝,這是更清潔! – mcluka

+0

@mcluka歡迎您!不要擔心倒票...有時候,即使他們錯了,你也可以控制他人的想法 –

+0

@mcluka不用擔心,有時我也不明白,但是當我看到類似的東西時,我嘗試修復它,所以我投了你的問題,因爲它是一個很好的例子,簡短的代碼示例,顯示的努力,我的意思是,它擁有一切......我很高興我可以幫助你,不要忘記接受,如果它是幫助,我一直都很喜歡幫助 –