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

2024-10-01 22:26:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图编写一个程序,以便将华氏度转换为摄氏度。我的代码的输出应该类似于“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()

Tags: 代码程序inputdef数字floatenterdegrees
1条回答
网友
1楼 · 发布于 2024-10-01 22:26:43

仅计算值是不够的,您还需要返回它:

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开发人员如何用更简单的代码达到同样的目的是很有用的

相关问题 更多 >

    热门问题