Python 温度转换器代码 - 摄氏度和华氏度互转
以下是一个简单的 Python 温度转换器代码,可以将摄氏温度转换为华氏温度或将华氏温度转换为摄氏温度:
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5/9
while True:
choice = input('请选择转换类型:\n1. 摄氏温度转换为华氏温度\n2. 华氏温度转换为摄氏温度\n3. 退出\n')
if choice == '1':
celsius = float(input('请输入摄氏温度: '))
converted_fahrenheit = celsius_to_fahrenheit(celsius)
print('摄氏温度 %.2f°C 转换为华氏温度为 %.2f°F\n' % (celsius, converted_fahrenheit))
elif choice == '2':
fahrenheit = float(input('请输入华氏温度: '))
converted_celsius = fahrenheit_to_celsius(fahrenheit)
print('华氏温度 %.2f°F 转换为摄氏温度为 %.2f°C\n' % (fahrenheit, converted_celsius))
elif choice == '3':
print('程序已退出。')
break
else:
print('无效的选择,请重新输入。\n')
您可以运行此代码,在菜单中选择要进行的转换类型并按照提示输入温度值,程序将会打印出转换后的温度值。选择'3'会退出程序。
原文地址: https://www.cveoy.top/t/topic/Nsk 著作权归作者所有。请勿转载和采集!