python中温度单位转换的实例方法
2020-12-27 11:52:24
温度有摄氏度和华氏度两个单位,我们通常使用的是摄氏度,对于转换成华氏度,很多小伙伴记不住公式。作为万能的计算机,它是可以帮助我们解决温度单位转换的问题。本文主要演示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中温度单位如何转换内容请搜索IT技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT技术网!
相关阅读
- 用python对excel进行操作(读,写,修改)
- 使用Python实现音频双通道分离
- 通过python-pptx模块操作ppt文件的方法
- python Pexpect模块的使用
- python语言time库和datetime库基本使用详解
- Python新建项目自动添加介绍和utf-8编码的方法
- Python 可视化神器Plotly详解
- python中str内置函数用法总结
- python中温度单位转换的实例方法
- python函数超时自动退出的实操方法
- Python 利用argparse模块实现脚本命令行参数解析
- 一个非常简单好用的Python图形界面库(PysimpleGUI)
- python字典按照value排序方法
- python字典与json转换的方法总结
- python获取天气接口给指定微信好友发天气预报
- 详解python 条件语句和while循环的实例代码
- python Timer 类使用介绍
- Python+kivy BoxLayout布局示例代码详解