【发布时间】:2021-10-19 10:55:57
【问题描述】:
我正在制作这款二十一点游戏,我敢肯定,如果你玩过这款游戏,你就会知道规则。基本上我有 5 个筹码,我让用户输入他们的赌注。我有这个 try catch 块,它应该不允许用户输入低于 0 和高于 chip_amount 的任何内容。我对ValueError 的例外工作正常,如果用户键入“fff”或任何不是数字的内容,while 循环将继续。如果用户输入低于 0 或高于 chip_amount 的任何内容,程序将退出,这是因为 while 循环停止并且我无法将 continue 放入我的 if 测试中,我该如何解决这个问题?
print("\n==== BLACKJACK GAME ====")
print(f'\nYou have currently have {chip_amount} chips available.')
while True:
try:
chips_input = int(input("How many chips do you want to bet? "))
if chips_input < 1:
raise Exception("Sorry, you have to enter a number bigger than 1.")
if chips_input > chip_amount:
raise Exception(f'Sorry, you have to enter a number less than {chip_amount}.')
except ValueError:
print("\nYou have to enter a number!")
continue
else:
print(f'\nYou bet {chips_input} chips out of your total of {chip_amount} chips.')
print(f'\nThe cards have been dealt. You have a {" and a ".join(player_hand)}, with a total value of {player_total}.')
print(f'The dealers visible card is a {dealer_hand[0]}, with a value of {dealer_total_sliced}.')
【问题讨论】:
-
Exception将中断 while 循环。为什么不直接用print语句替换它?