2016-09-08 9 views
0

Helloスタックオーバーフローコミュニティ。Pythonの 'except'節が動作しない

私は現在、Python(3.5)でプログラミングする方法を学習しようとしており、変換プログラムに問題がありました。要約すると、Pythonはソースコードのexcept節を無視しているようです。

try: 
    print("Welcome to CONVERSION. Choose an option.") 
    print("1. Convert CELSIUS to FAHRENHEIT.") 
    print("2. Convert FAHRENHEIT to CELSIUS.") 
    Option = int(input("OPTION: ")) 
except NameError: 
    print(Option, " is not a valid input.") 
except ValueError: 
    print(Option, " is not a valid input.") 
except KeyboardInterrupt: 
    print("Don't do that!") 
else: 
    if (Option != 1) or (Option != 2): 
     print("Please input a valid option!") 
    elif (Option == 1): 
     try: 
      Celsius = float(input("Enter value in Celsius: ")) 
     except ValueError: 
      print(Celsius, " is not a valid input.") 
     except KeyboardInterrupt: 
      print("Don't do that!") 
     else: 
      Fahrenheit = Celsius * 1.8 + 32 
     print(Celsius, "C = ", Fahrenheit, "F.") 
    elif (Option == 2): 
     try: 
      Fahrenheit = float(input("Enter value in Fahrenheit: ")) 
     except ValueError: 
      print(Celsius, " is not a valid input.") 
     except KeyboardInterrupt: 
      print("Don't do that!") 
      Celsius = (Fahrenheit - 32) * (5/9) 
      print(Fahrenheit, "F = ", Celsius, "C.") 
     else: 
      print("That value is invalid. Try again.") 

フルトレースバック、最初の画面に値「WAD」を入力

:あなたは、例外をキャッチした後、例外がスローされ

Traceback (most recent call last): 
File "C:\Users\user\Documents\Visual Studio 2015\Projects\TempConversion\TempConversion\TempConversion.py", line 7, in <module> 
Option = int(input("OPTION: ")) 
ValueError: invalid literal for int() with base 10: 'wad' 

During handling of the above exception, another exception occurred: 

Traceback (most recent call last): 
File "C:\Users\user\Documents\Visual Studio 2015\Projects\TempConversion\TempConversion\TempConversion.py", line 11, in <module> 
print(Option, " is not a valid input.") 
NameError: name 'Option' is not defined 
+0

エラーを慎重に読んでください:プログラムは "wad"を7行目の整数に変換しようとしますが、これは失敗します。整数変換が失敗したため、オプションが定義されていないため、エラーをキャッチして11行目とエラーを返します。だからあなたの意見をきめ細かくしてください。 – ChE

+0

int( 'wad') 'がエラーを返すので、' Option'は決して定義されません。これを処理している間は、再び定義されていない 'Option'を出力しようとします。この時間は処理されない別のエラーが発生します。それはうまく動作します☺ –

+0

質問自体には関係ありませんが、Pythonの規約は関数/変数のlower_caseとクラス名のUpperCaseです。また、if条件の周りに括弧は必要ありません。 – viraptor

答えて

4

。これは、基本的にtry catchのシナリオの外側に置きます。

tryの前にOption = Noneを追加すると、コードが正しく実行されます。

理由は、int(input(...))がOptionが定義される前に例外を発生させるためです。そのため、最初の例外を処理するコードが新しい例外をスローしています。

Optionsの可能性のある値Noneを適切に処理するには、例外処理の中でprintステートメントを変更する必要があります。あなたはこれに似た何かによってこれを達成することができます。

Option = None 
try: 
    Option = int(input("OPTION: ")) 
except (NameError, ValueError): 
    if Option: 
     print(Option, " is not a valid input.") 
    else: 
     print("No valid input.") 
except KeyboardInterrupt: 
    print("Don't do that!") 
else: 
    ..... 

これは、摂氏と華氏と同じようなコードにも当てはまります。

[編集]新しい質問があなたの元の質問の範囲を超えているので理想的には新しい質問を作成するのが理想的ですが、私はあなたの質問に基づいて、コード。

import sys 


def get_input(text, convert_to='int'): 
    result = None 
    try: 
     if convert_to == 'int': 
      result = int(input(text)) 
     else: 
      result = float(input(text)) 
    except (NameError, ValueError): 
     if result: 
      print(result, " is not a valid input.") 
     else: 
      print("No valid input.") 
     sys.exit(1) 

    return result 


def handle_celsius_to_fahrenheit(): 
    celsius = get_input('Enter value in Celsius: ', convert_to='float') 
    fahrenheit = celsius * 1.8 + 32 
    print("C = %s, F %s." % (celsius, fahrenheit)) 


def handle_fahrenheit_to_celsius(): 
    fahrenheit = get_input('Enter value in Fahrenheit: ', convert_to='float') 
    celsius = (fahrenheit - 32) * (5/9) 
    print('F = %s , C %s.' % (fahrenheit, celsius)) 


def get_option(): 
    option = get_input('OPTION: ') 
    if option == 1: 
     handle_celsius_to_fahrenheit() 
    elif option == 2: 
     handle_fahrenheit_to_celsius() 
    else: 
     print("Please input a valid option!") 
     sys.exit(1) 

if __name__ == '__main__': 
    print("Welcome to CONVERSION. Choose an option.") 
    print("1. Convert CELSIUS to FAHRENHEIT.") 
    print("2. Convert FAHRENHEIT to CELSIUS.") 
    get_option() 
+1

私はまた、最初の 'print'ステートメントを' try'の外に移動します。そこに_try_は何もないので、 –

+0

は同意します。それらのプリントステートメントをラップする理由はありません。 – eandersson

+1

それはうまくいった!どうもありがとうございます。 – Walrus

2

あなたはエラーとあなたの文字列に変数Optionを使用しようとしているが、それはエラーの理由だとして、その変数は、存在しません。 tryの前にOption = input()を開始し、それをintに変換してください。try

0

これは正常に機能します。 ValueError例外を処理しているときは、まだ設定されていないOptionを読み込もうとします。これは別の例外をもたらす。あなたはもはやそれを捕まえません。

関連する問題