这篇文章将为大家详细讲解有关利用python怎么对温度的单位进行转换,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
一、问题
温度有摄氏度(Celsius)和华氏度(Fabrenheit)两个不同的单位。摄氏度0度为结冰点,沸点为100度;华氏度以32度为冰点,以212度为沸点。一般来说,中国采用摄氏度,美国采用华氏度。
两者之间的转换公式为:摄氏度=(华氏度-32)/1.8、华氏度=摄氏度*1.8+32。
输入
#定义一个函数获取带符号的温度值。
def tempstr():
while True:
temp=input('请输入带有符号[C代表摄氏度,F代表华氏度]的温度数值:')
if temp[-1] in ['c','C','f','F']:
return temp
else: #如果输入的温度值没有带有符号,会提示输入错误并被要求重新输入。
print('输入错误,请输入带有符号的温度数值')
print('-'*20)
处理输出
#定义一个函数获取带符号的温度值。
def tempstr():
while True:
temp=input('请输入带有符号[C代表摄氏度,F代表华氏度]的温度数值:')
if temp[-1] in ['c','C','f','F']:
return temp
else: #如果输入的温度值没有带有符号,会提示输入错误并被要求重新输入。
print('输入错误,请输入带有符号的温度数值')
print('-'*20)
总体代码
def tempstr():
while True:
temp=input('请输入带有符号[C代表摄氏度,F代表华氏度]的温度数值:')
if temp[-1] in ['c','C','f','F']:
return temp
else:
print('输入错误,请输入带有符号的温度数值')
print('-'*20)
def progress(temp):
if temp[-1] in ['F','f']:
output=(eval(temp[:-1])-32)/1.8
print('温度转换为摄氏度为{:.2f}C'.format(output))
else:
output=eval(temp[:-1])*1.8+32
print('温度转换为华氏度为{:.2f}F'.format(output))
temp=tempstr()
progress(temp)
温度单位转换实例扩展:
module:temp
def temp_f_to_c(f):
return (f - 32) * (5 / 9)
def temp_c_to_f(c):
return (c * 9 / 5) + 32
def main():
print(temp_c_to_f(100))
if __name__ == '__main__':
main()
main function:
import temps
def convert_temp_system(temp, temp_system):
if temp_system == 'c':
new_temp = temps.temp_c_to_f(temp)
else:
new_temp = temps.temp_f_to_c(temp)
return new_temp
def print_temp_message(original_temp, new_temp, system):
if system == 'f':
print(original_temp, 'degrees F converted to C is ', new_temp)
else:
print(original_temp, 'degrees C converted to F is ', new_temp)
def main():
temp = float(input('Enter the temperature: '))
system = input('F or C: ')
converted_temp = convert_temp_system(temp, system)
print_temp_message(temp, converted_temp, system)
if __name__ == '__main__':
main()
关于利用python怎么对温度的单位进行转换就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。