当前位置 博文首页 > python中温度单位转换的实例方法

    python中温度单位转换的实例方法

    作者:宋宋大人 时间:2021-02-17 09:08

    温度有摄氏度和华氏度两个单位,我们通常使用的是摄氏度,对于转换成华氏度,很多小伙伴记不住公式。作为万能的计算机,它是可以帮助我们解决温度单位转换的问题。本文主要演示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()
    js
    下一篇:没有了