如何在我的 while 循环中继续我的 try/catch

How do I continue my try/catch in my while-loop

我正在制作这款 21 点游戏,我相信如果您玩过这款游戏,您就会知道规则。基本上我有 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}.')

我猜你说“while loop stops”是指程序以 Exception 退出。这是因为您只排除了 ValueError 异常,但是您引发了 Exception,所以它没有被捕获并且错误终止了程序。

无论如何,使用一般 Exception 是不好的做法。你应该使用从 https://docs.python.org/3/library/exceptions.html

中选择一个具体的 Exception

你可能会选择 ValueError 并用你当前的 except 块捕获它们

引发 ValueErrors 以便您的 except 块也能捕获这些错误:

if chips_input < 1:
    raise ValueError("Sorry, you have to enter a number bigger than 1.")
if chips_input > chip_amount:
    raise ValueError(f'Sorry, you have to enter a number less than {chip_amount}.')

您可以在回复有效时循环,而不是无限 while True 循环

chip_amount = 10

print("\n==== BLACKJACK GAME ====")
print(f'\nYou have currently have {chip_amount} chips available.')
chips_input = input("How many chips do you want to bet? ")

while not chips_input.isdigit() or not chip_amount >= int(chips_input) >= 0:
    print(f"False entry, enter a number between 0 and {chip_amount}")
    chips_input = input("How many chips do you want to bet? ")

print(f'\nYou bet {chips_input} chips out of your total of {chip_amount} chips.')