Python 我应该如何在像华氏到摄氏度这样的方程式中使用用户输入?当我运行代码时,它说这是转换行
我对编码相当陌生,所以他们还有其他改进方法吗?在这一行中,您将测量用户输入的温度,并将其存储在一个名为Python 我应该如何在像华氏到摄氏度这样的方程式中使用用户输入?当我运行代码时,它说这是转换行,python,Python,我对编码相当陌生,所以他们还有其他改进方法吗?在这一行中,您将测量用户输入的温度,并将其存储在一个名为华氏的变量中 #taking temperature in fahrenheit fahrenheit = float(input("Enter temperature degrees in fahrenheit:")) #Coversion formula conv_for = (input - 32) * 5/9 #calculation for celcius celcius = co
华氏
的变量中
#taking temperature in fahrenheit
fahrenheit = float(input("Enter temperature degrees in fahrenheit:"))
#Coversion formula
conv_for = (input - 32) * 5/9
#calculation for celcius
celcius = conv_for
print("%02f degrees in fahrenheit is equal to %02f degrees in celcius")
因此,如果用户输入,比如说,76
,那么fahrenheit
将存储值76
。然而,在这一行中,您使用的是input
,而不是fahrenheit
#taking temperature in fahrenheit
fahrenheit = float(input("Enter temperature degrees in fahrenheit:"))
input
本质上是一个函数,它接受用户输入的内容并将其存储。我想你真正想要的是,不要使用输入
,而是使用华氏
。为了清晰起见,我们将其指定为摄氏度
,而不是conv_。以下是上述内容的更正版本:
#Coversion formula
conv_for = (input - 32) * 5/9
类似地,print语句需要指定每个点的变量:
celsius = (fahrenheit - 32) * 5/9
您也可以像以前一样执行此操作,然后将其四舍五入到小数点后2位(这就是02
的意思):
在这一行中,您将获取用户输入的温度,并将其存储在名为华氏温度
的变量中
#taking temperature in fahrenheit
fahrenheit = float(input("Enter temperature degrees in fahrenheit:"))
#Coversion formula
conv_for = (input - 32) * 5/9
#calculation for celcius
celcius = conv_for
print("%02f degrees in fahrenheit is equal to %02f degrees in celcius")
因此,如果用户输入,比如说,76
,那么fahrenheit
将存储值76
。然而,在这一行中,您使用的是input
,而不是fahrenheit
#taking temperature in fahrenheit
fahrenheit = float(input("Enter temperature degrees in fahrenheit:"))
input
本质上是一个函数,它接受用户输入的内容并将其存储。我想你真正想要的是,不要使用输入
,而是使用华氏
。为了清晰起见,我们将其指定为摄氏度
,而不是conv_。以下是上述内容的更正版本:
#Coversion formula
conv_for = (input - 32) * 5/9
类似地,print语句需要指定每个点的变量:
celsius = (fahrenheit - 32) * 5/9
您也可以像以前一样执行此操作,然后将其四舍五入到小数点后2位(这就是02
的意思):
以下是更正后的代码:
print("%.02f degrees in fahrenheit is equal to %.02f degrees in celsius" % (fahrenheit, celsius))
以下是更正后的代码:
print("%.02f degrees in fahrenheit is equal to %.02f degrees in celsius" % (fahrenheit, celsius))
好的,第一件事缩进在python中很重要,所以要小心,
好的,第一件事缩进在python中很重要,所以要小心,
你有一个额外的缩进。通常最好包含完整的错误消息,这样人们可以看到哪里出了问题。你有一个额外的缩进。通常最好包含完整的错误消息,这样人们可以看到哪里出了问题。啊,好的。非常感谢你。使用f“{fahrenheit}…”和使用%02f有什么区别?不客气!好问题——我已经更新了我的答案,以反映我使用f
的方式是Python的一个更新功能,它更干净一些,但是我在我的答案中添加了如何按照预期的方式进行操作(它还有一个优点,就是把结果四舍五入到小数点后2位,所以像33.259这样的数字就会变成33.26)。如果你不在乎四舍五入,你可以交替使用它们。啊,好的。非常感谢。使用f“{fahrenheit}”有什么区别使用%02f?不客气!好问题-我更新了我的答案,以反映我使用f
的方式是Python较新的功能,它更干净,但我在我的答案中添加了如何按照您预期的方式进行操作(它还有一个优点,就是将结果四舍五入到小数点后2位,所以像33.259这样的数字只会变成33.26)。如果你不在乎四舍五入,你可以互换使用它们。