Python转换温度错误

时间:2016-05-19 08:28:57

标签: python syntax-error

我尝试编写此代码将温度从华氏温度转换为摄氏温度,反之亦然。

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"

但是我似乎在第5行得到了错误,我已经定义了celtofah函数。

enter image description here

我不认为缩进在这里是错误的,虽然我可能会错过任何东西。

2 个答案:

答案 0 :(得分:4)

这是你的缩进,即使没有看你的形象。 为了使它工作,您可以简单地缩进所有def和if / elif。 但更好的是,如果你在try / except之前定义那些函数,转换和if之后的else中的if / elif和除了ValueError之外的except更改。你也应该使用函数的参数,你使用的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)

还有一些其他的事情你可以改进你的代码,也许我错过了,但这可以作为模板。

答案 1 :(得分:3)

问题是try / except缩进,如果比较(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"