错误处理所需的输入

时间:2017-10-19 13:38:47

标签: python python-3.x error-handling

我试图用Python编写Blackjack纸牌游戏。 在玩家类中,我想定义一个循环,要求玩家决定“击中”#34;或者"站立" (二十一点规则)。除非输入正确(对于立场是“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' H'),否则会产生错误,但到目前为止,代码并不起作用正确地......我认为有一个小小的故障......

任何提案? 亲切的问候,

2 个答案:

答案 0 :(得分:2)

你应该写:

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 :(得分: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