Python转换温度报错

标签 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

我不认为这里的缩进是错误的,尽管我可能会遗漏一些东西。

最佳答案

这是你的缩进,即使不看你的形象。 要使其工作,您可以简单地缩进所有 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/

相关文章:

python - 发送串口中断 'character'(唤醒调用)

python - 处理多个相同类型的异常并在 python 中恢复执行

python - Pycharm:如何调整变量/语法突出显示的颜色?

syntax-error - 汽车 : + is not a list, 口齿不清错误?

ON DELETE CASCADE 的 MySQL 语法错误 #1064

c++ - 自相矛盾的错误消息 - 运算符重载 <<

python - BeautifulSoup 返回意外的额外空格

python - 如何在 Google App Engine 中使用 Python(和 boto)通过浏览器从 Amazon S3 下载文件?

extjs4 - Extjs SyntaxError : invalid property id

编译错误/查询