Python问题:使用if尝试和例外

时间:2016-11-22 17:16:52

标签: python if-statement try-except

这可能是非常基本但我试图触发Except如果cointype()不在字典coin_int内,则它会直接跳出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...")

3 个答案:

答案 0 :(得分:3)

你想提出例外。刚

import * as jwt from 'angular2-jwt/angular2-jwt';

答案 1 :(得分:2)

首先你永远不会达到你的...你不会“尝试”任何会引发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)

如果你真的想要停止程序执行,那么在except:

中执行以下任何操作
  • raise提出使用默认消息
  • 捕获的感知
  • raise ValueError("That value of coin is not accepted, try again and choose from", coin_int)也可以在else中用于使用自定义消息引发特定异常

答案 2 :(得分:0)

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

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))