【问题标题】:Required input with error handling带有错误处理的必需输入
【发布时间】:2018-03-31 13:47:03
【问题描述】:

我正在尝试用 Python 编写二十一点纸牌游戏。 在玩家类中,我想定义一个循环,要求玩家决定“击中”或“站立”(二十一点规则)。除非输入正确(“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”),否则会产生错误,但到目前为止,代码还不能正常工作......我认为有一个小故障....

有什么建议吗? 亲切的问候,

L

【问题讨论】:

  • 你知道吗? 'Foo' in ['S', 'H'] is False 评估为?这可能会让你大吃一惊。
  • 除了你还有什么期待?除了块,你应该期待尝试中的一些东西

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


【解决方案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 

【讨论】:

    【解决方案2】:

    这里不需要例外,你可以这样做:

    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
    

    【讨论】:

    • 谢谢,这更干净了!
    • @mcluka 欢迎您!不用担心投反对票...有时您可以控制人们的想法,即使他们错了
    • @mcluka 别担心,有时我也不明白,但是当我看到类似的东西时,我会尝试修复它,所以我投票赞成你的问题,因为它是一个非常好的问题,例如,简短的代码示例,显示努力,我的意思是,它拥有一切......我很高兴我能帮助你,如果它有帮助别忘了接受,我一直很喜欢帮助跨度>
    猜你喜欢
    • 2020-09-24
    • 1970-01-01
    • 2021-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多