Python 问题:Try and Except with if

Python Issue: Try and Excepts with if

这可能是非常基本的,但如果 cointype() 不在字典 coin_int 中,我会尝试触发 Except 到 运行 但它会直接跳出if 条件而不使用 Except 即使遇到值错误? 感谢您的帮助。

try:
    coin_type = input("Input your coin: 1p, 2p, 5p etc...  ")
    if coin_type in coin_int:
        print("That value is recognised inside the list of known coin types")

except ValueError:
    print("That value of coin is not accepted, restarting...")

您想引发 异常。刚刚

raise ValueError("wrong coin type")

您的程序应该如下所示。 (我通过列表而不是字典给出示例)

coin_int = ['1p', '2p', '3p', '4p', '5p']
try:
    coin_type = '6p'
    if coin_type in coin_int:
        print("That value is recognised inside the list of known coin types")
    else:
        raise ValueError("wrong coin type")
except ValueError as error:
    print("That value of coin is not accepted, restarting..." + repr(error))

首先,您的 except 将永远无法到达...您不会 "try" 任何会引发 ValueError 异常的东西...让我先展示如何做到这一点,然后基本上说在这种情况下您使用 try/except:

不会有任何收获
coin_int = ("1p", "2p", "5p")
while True:
    coin_type = input("Input your coin: 1p, 2p, 5p etc.: ")
    try:
        coin_int.index(coin_type)
        print("value accepted, continuouing...")
        break
    except ValueError:
        print("That value of coin is not accepted, try again and choose from", coin_int)

但这是等价的,在这种情况下同样有效(如果在性能和可读性方面不是更好的话):

coin_int = ("1p", "2p", "5p")
while True:
    coin_type = input("Input your coin: 1p, 2p, 5p etc.: ")
    if coin_type in coin_int:
        print("value accepted, continuouing...")
        break
    else:
        print("That value of coin is not accepted, try again and choose from", coin_int)

如果您真的想停止程序执行,请执行以下任何操作,除了:

  • raise 引发使用默认消息捕获的异常
  • raise ValueError("That value of coin is not accepted, try again and choose from", coin_int) 也可以在 else 中使用以通过自定义消息
  • 引发特定异常