基于Python实现温度转换程序
作者:星尘库
这篇文章主要为大家详细介绍了如何基于Python实现简单的温度转换程序,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
1.使用pycharm运行温度转换程序,尝试将温度单位设在前面
2.参照温度转换程序,自己写一个关于货币转换、长度转换、重量转换或者面积转换的程序
循环+函数
def convertemperature():
temperature = ""
while (temperature != "q"):
temperature = input("请输入带有符号的温度:")
if (temperature[-1] in ['f', 'F']):
C = (eval(temperature[0:-1]) - 32) / 1.8
print("转换后的温度是{:.2f}C".format(C))
print("退出请输入q")
elif (temperature[-1] in ['c', 'C']):
C = (1.8 * eval(temperature[0:-1]) + 32)
print("转换后的温度是{:.2f}C".format(C))
else:
print("输入格式错误")
print("退出请输入q")
convertemperature()循环 +异常处理 温度单位设在前面 f代表华氏度 c代表摄氏度---函数里面循环
def convertemperature():
temperature = ""
while (temperature != "exit"):
temperature = input("请输入带有符号的温度:")
if (temperature[0] in ['f', 'F']):
try:
C = (eval(temperature[1:]) - 32) / 1.8
print("转换后的温度是{:.2f}C".format(C))
except:
print("转换失败,请重新输入")
print("退出请输入exit")
elif (temperature[0] in ['c', 'C']):
try:
C = (1.8 * eval(temperature[1:]) + 32)
print("转换后的温度是{:.2f}C".format(C))
except:
print("转换失败,请重新输入")
print("退出请输入exit")
else:
print("输入格式错误")
print("退出请输入exit")
# 循环 +异常处理 温度单位设在前面 f代表华氏度 c代表摄氏度
convertemperature()循环里面使用函数
temperature=""
while (temperature != "q"):
temperature = input("请输入带有符号的温度:")
convertemperature2(temperature)
def convertemperature2(aa):
temperature = aa
if (temperature[0] in ['f', 'F']):
try:
C = (eval(temperature[1:]) - 32) / 1.8
print("转换后的温度是{:.2f}C".format(C))
except:
print("转换失败,请重新输入")
print("退出请输入q")
elif (temperature[0] in ['c', 'C']):
try:
C = (1.8 * eval(temperature[1:]) + 32)
print("转换后的温度是{:.2f}C".format(C))
except:
print("转换失败,请重新输入")
print("退出请输入q")
else:
print("输入格式错误")
print("退出请输入q")重量转换
# 货币转换、长度转换 、重量转换或者面积转换
temperature = ""
while temperature != "q":
temperature = input("请输入带有符号的重量:")
print(temperature[-2:])
if temperature[-2:] in ['kg', "Kg", "KG", "kG"]:
try:
C = (eval(temperature[0:-2]) * 1000)
print("转换后的重量是{:.2f}克".format(C))
except:
print("转换失败,请重新输入")
print("退出请输入q")
elif temperature[-1] in ['g', 'G']:
try:
C = (eval(temperature[0:-1]) / 1000)
print("转换后的重量是{:.2f}千克".format(C))
except:
print("转换失败,请重新输入")
print("退出请输入q")
else:
print("输入格式错误")
print("退出请输入q")
# 循环 +异常处理 重量转换模仿例子程序,编写英寸和厘米的转换程序,1inch=2.54cm。比如,输入3.2i则输出8.13 c,输入4.5c则输出1.77i,输入4.5k输出“输入格式错误”。
temperature = ""
while temperature != "q":
temperature = input("请输入带有符号的尺寸:eg:3.2i \n")
if temperature[-1:] in ['i', 'I']:
try:
C = (eval(temperature[0:-1]) * 2.54)
print("转换后是{:.2f}c".format(C))
except:
print("转换失败,请重新输入")
print("退出请输入q")
elif temperature[-1] in ['c', 'C']:
try:
C = (eval(temperature[0:-1]) / 2.54)
print("转换后是{:.2f}i".format(C))
except:
print("转换失败,请重新输入")
print("退出请输入q")
else:
print("输入格式错误")
print("退出请输入q")到此这篇关于基于Python实现温度转换程序的文章就介绍到这了,更多相关Python温度转换内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
