我尝试编写此代码以将温度从华氏度转换为摄氏度,反之亦然。
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 函数时出错。
我不认为这里的缩进是错误的,尽管我可能会遗漏一些东西。
最佳答案
这是你的缩进,即使不看你的形象。 要使其工作,您可以简单地缩进所有 def 和 if/elif。 但更好的是,如果您在 try/except 之前定义这些函数,则在 except 之后的 else 中定义转换和 if/elif,并将 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)
您的代码还有一些其他地方可以改进,也许还有我遗漏的地方,但这可以作为模板。
关于Python转换温度报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37317848/