繁体   English   中英

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

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

我正在制作这款 21 点游戏,我相信如果您玩过这款游戏,您就会知道规则。 基本上我有 5 个筹码,我让用户输入他们的赌注。 我有这个 try catch 块,应该不会让用户输入低于 0 和高于chip_amount任何chip_amount 我的ValueError异常工作正常,如果用户键入“fff”或任何不是数字的内容,while 循环将继续。 如果用户输入低于 0 和高于chip_amount任何内容,程序将退出,这是因为 while 循环停止并且我无法在 if 测试中放置continue ,我该如何解决这个问题?

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}.')

提高 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.')

我猜当您说“while 循环停止”时,您的意思是程序以Exception退出。 这是因为您只是排除ValueError异常,但您引发了一个Exception ,因此它不会被捕获并且错误会终止程序。

无论如何使用通用Exception是不好的做法。 您应该使用从https://docs.python.org/3/library/exceptions.html 中选择一个具体的Exception

您可能可以使用ValueError并使用当前的except块捕获它们

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM