python - 错误处理所需的输入

标签 python python-3.x error-handling

我正在尝试用 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”),否则会产生错误,但到目前为止,代码还不能正常工作......我认为有一个小故障....

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

大号

最佳答案

你应该写:

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

而且整个代码会更短且更易读,无一异常(exception):

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 

关于python - 错误处理所需的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46831297/

相关文章:

python - 匹配字符串结尾

python - 如何在 Pygame 中制作圆形倒数计时器?

python-3.x - 我们可以在 pyside 中发出基类的信号吗?

python-3.x - 调用 CF API 登录一次性密码时出错

python-3.x - 导入父目录进行简单测试

php - 无效的链接: Cannot load presenter 'Post' , class 'App\Presenters\PostPresenter' was not found

powershell - Get-Hotfix引发Get-HotFix : Provider load failure

python - 无法访问 const char 数组的值

linux - 通过 shell 自动化脚本编辑 .CSV 文件

python - 导入模块时的奇怪行为