Python 使用定义的函数将华氏度转换为摄氏度的程序

Python 使用定义的函数将华氏度转换为摄氏度的程序,python,Python,我正试图编写一个程序,以便将华氏度转换为摄氏度。我的代码的输出应该类似于“212.0华氏度=100.0摄氏度”。但是,当我执行代码时,它显示的不是摄氏度部分的数字,而是“无摄氏度” 下面是我的代码: Fahrenheit = float(input('Enter degrees Fahrenheit: ')) def computeCelsius(): (Fahrenheit - 32) * (5 / 9) celsius = computeCelsius() def pri

我正试图编写一个程序,以便将华氏度转换为摄氏度。我的代码的输出应该类似于“212.0华氏度=100.0摄氏度”。但是,当我执行代码时,它显示的不是摄氏度部分的数字,而是“无摄氏度”

下面是我的代码:

Fahrenheit = float(input('Enter degrees Fahrenheit: '))


def computeCelsius():
    (Fahrenheit - 32) * (5 / 9)


celsius = computeCelsius()


def printResult():
    print(
        str(Fahrenheit) + ' degrees Fahrenheit = ' + str(celsius) +
        ' degrees Celsius ')


computeCelsius()
printResult()
仅计算值是不够的,还需要返回:

def computeCelsius(fahren):
    return (fahren - 32) * 5 / 9
如果函数没有显式返回某些内容,它将隐式返回
None
。您会注意到,我还将华氏温度作为参数传递,而不是使用全局变量。这是一个很好的实践,允许您转换任何值或变量,而不必首先将其加载到全局变量中

您可能会发现,使用更现代的Python功能(如f字符串)并关闭相关代码,检查下面的重写非常有用:

def computeCelsius(fahren):
    return (fahren - 32) * 5 / 9

fahrenheit = float(input('Enter degrees Fahrenheit: '))
celsius = computeCelsius(fahrenheit)
print(f"{fahrenheit}°F = {celsius}°C")

如果这是一个类作业,我不会把它当作你自己的工作,但是了解一个经验丰富的Python开发人员如何用更简单的代码达到同样的目的是很有用的。

有没有具体的问题?你做过调试吗?我建议你读书。请看。