2016-11-22 22 views
1

場合、これはおそらく非常に基本的なものですが、私はcointype()辞書coin_int内にない場合に実行するExceptをトリガしようとしていますが、それは使用せずにまっすぐif条件の飛び出しを試してみて、exceptsでExcept場合でも、値のエラーは満たされていますか? ありがとうございました。Pythonの問題:

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

答えて

2

は、まずあなた到達することはありませんを除いて...あなたは私が最初にどのようにお見せしましょう...とValueErrorの例外が発生します何かを「試す」はありません(私の代わりに、辞書のリストを例を挙げています)

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) 

しかし、これは同等であり、この場合には、同じように効率的な(そうでない場合は、より良い、実際に両方のパフォーマンスにして:これまで、その後、基本的にはこのような場合には、あなたがするtry/exceptを使用して何かを得ていないことを言います可読性):

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) 

あなたが本当に除いに次のいずれかの操作を行い、その後、プログラムの実行を停止する場合:また、調達するelseで使用することができ、デフォルトのメッセージ

  • raise ValueError("That value of coin is not accepted, try again and choose from", coin_int)でキャッチexcceptionを高めるために

    • raiseカスタムメッセージでの特定の例外
  • 3

    あなたは昇給例外にしたいです。ちょうど

    raise ValueError("wrong coin type") 
    
    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))