我正试图编写一个程序,以便将华氏度转换为摄氏度。我的代码的输出应该类似于“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()
仅计算值是不够的,您还需要返回它:
如果函数没有显式地返回某个内容,它将隐式地返回
None
。您会注意到,我还将华氏温度作为参数传递,而不是使用全局变量。这是一个很好的实践,允许您转换任何值或变量,而不必首先将其加载到全局变量中您可能会发现,使用更现代的Python功能(如f字符串)并关闭相关代码,检查下面的重写非常有用:
如果这是一个类工作任务,我不会把它当作你自己的工作,但是了解一个经验丰富的Python开发人员如何用更简单的代码达到同样的目的是很有用的
相关问题 更多 >
编程相关推荐