我正在尝试用 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/