温度有摄氏度和华氏度两个单位,我们通常使用的是摄氏度,对于转换成华氏度,很多小伙伴记不住公式。作为万能的计算机,它是可以帮助我们解决温度单位转换的问题。本文主要演示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中温度单位转换的实例方法的文章就介绍到这了,更多相关python中温度单位如何转换内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!