Python问题:尝试使用if
这可能是非常基本的,但是如果Python问题:尝试使用if,python,if-statement,try-except,Python,If Statement,Try Except,这可能是非常基本的,但是如果cointype()不在字典coin\u 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
cointype()
不在字典coin\u 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")
您想引发一个异常。只是
raise ValueError("wrong coin type")
你的程序应该是这样的。(我通过列表而不是字典给出示例)
你的程序应该是这样的。(我通过列表而不是字典给出示例)
首先,你的“例外”永远无法联系到。。。您不会“尝试”任何会引发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)
但这是等效的,在这种情况下同样有效(如果在性能和可读性方面实际上没有更好的话):
如果确实要停止程序执行,请在中执行以下任一操作,除非:
引发默认消息捕获的例外raise
,它也可用于raisevalueerror(“该硬币的价值不被接受,请重试并从中选择”,coin_int)
中,以通过自定义消息引发特定异常其他
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)
但这是等效的,在这种情况下同样有效(如果在性能和可读性方面实际上没有更好的话):
如果确实要停止程序执行,请在中执行以下任一操作,除非:
引发默认消息捕获的例外raise
,它也可用于raisevalueerror(“该硬币的价值不被接受,请重试并从中选择”,coin_int)
中,以通过自定义消息引发特定异常其他