【问题标题】:How do I continue my try/catch in my while-loop如何在我的 while 循环中继续我的 try/catch
【发布时间】: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 语句替换它?

标签: python try-catch


【解决方案1】:

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

【讨论】:

  • 我明白了,这行得通。唯一的问题是我无法使用我在 if 测试中编写的错误消息,有解决方案吗?
  • 不幸的是我没有关注。您可以编辑您的问题以包括您的单元测试吗?
  • 这是当前输出。假设我输入 0,它会立即跳转到异常您当前有 5 个筹码可用。你想下多少筹码? 0 你必须输入一个数字!你想下多少筹码?
  • 要么抛出一个不同的错误并添加一个额外的 except 块来捕获它以获得不同的消息,或者只是将当前的 except 消息更改为更通用的内容,例如“无效输入,请重试”跨度>
【解决方案2】:

您可以在回复有效时循环,而不是无限循环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.')

【讨论】:

    【解决方案3】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2019-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-24
      • 2014-09-11
      • 1970-01-01
      • 2017-10-09
      相关资源
      最近更新 更多