2016-05-19 8 views
2

私はこのコードを書き、温度を華氏から摂氏に、逆もまた逆に変換しようとしました。Pythonの温度エラーの変換

try: 
     temperature=raw_input ("Enter temperature in numerals only") 
     temp1=float(temperature) 
     conversion=raw_input ("Convert to (F)ahrenheit or (C)elsius?") 
def celtofah(): 
     temp2 = (9/5)*temp1+32 
     print temp1," C = ",temp2," F" 
def fahtocel(): 
     temp2 = (5/9)*(temp1-32) 
     print temp1," F = ",temp2," C" 
if conversion == F: 
     celtofah() 
elif conversion == C: 
     fahtocel() 

except: 
     print "Please enter a numeric value" 

しかし、私はceltofah関数を定義した行5でエラーが発生しているようです。

enter image description here

私は何かを逃すことができるが、インデントがここに間違っているとは思いません。

+0

*インデントが間違っているとは思わない* - してください** **必ずしもそうではありません。 – Idos

答えて

4

それも、あなたの画像を見ずに、自分のインデントです。 これを動作させるには、defとif/elifをすべてインデントするだけです。 しかし、try/exceptの前にこれらの関数を定義すると、さらに優れたものになります。elseのif/elifはexceptの後に、exceptはexcept ValueErrorに変更されます。また、関数のパラメータを使用する必要があり、使用するFとCは宣言されていない変数です。

def celtofah(temp1): 
    temp2 = (9/5)*temp1+32 
    print temp1," C = ",temp2," F" 
def fahtocel(temp1): 
    temp2 = (5/9)*(temp1-32) 
    print temp1," F = ",temp2," C" 

try: 
    temperature=raw_input ("Enter temperature in numerals only") 
    temp1=float(temperature) 
except ValueError: 
    print "Please enter a numeric value" 
else: 
    conversion=raw_input ("Convert to (F)ahrenheit or (C)elsius?") 
    if conversion == 'F': 
     celtofah(temp1) 
    elif conversion == 'C': 
     fahtocel(temp1) 

あなたのコードや、私が見逃したことがあるかもしれないが、これはテンプレートとして役立つことがあります。

+0

ありがとうございます!それも同様に働いた。 –

3

問題はインデントを除くと比較(CとFは文字列でなければなりません)場合/試みです:

try: 
    temperature = raw_input("Enter temperature in numerals only") 
    temp1 = float(temperature) 
    conversion = raw_input("Convert to (F)ahrenheit or (C)elsius?") 


    def celtofah(): 
     temp2 = (9/5) * temp1 + 32 
     print temp1, " C = ", temp2, " F" 


    def fahtocel(): 
     temp2 = (5/9) * (temp1 - 32) 
     print temp1, " F = ", temp2, " C" 


    if conversion == "F": 
     celtofah() 
    elif conversion == "C": 
     fahtocel() 

except: 
    print "Please enter a numeric value" 
+0

ありがとうございました!それはうまくいった。しかし、通常、tryブロックから関数を除外し、その中に入出力文だけを残すのは習慣ではありませんか?あなたが提供したソリューションのtryブロックに関数が入っていませんか? –

+0

はい、tryブロックのスコープ付き関数として作成します。そのようにしたくない場合は、 'def ...():'行を左端にインデントしてtryブロックの上にすべての関数を置いてください。 – cemper93

+0

はい、正しいですが、try/exceptは入力文だけをラップする必要があります。私が投稿した解決策は簡単な修正です、それを行う最善の方法は@MatthiasSchreiber投稿 – Roomm