Python实验1:温度转换与输入输出强化

知识点:input()/print()、分支语句、字符串处理(教材 2.1-2.2)实验任务:
1.实现投氏温度与华氏温度互转(保留两位小数)
2.扩展功能:输入错误处理(如非数字输入提示重新输入)

点击查看代码
TempStr = input("请输入带有符号的温度值(C/F):")
if TempStr[-1] in ['F', 'f']:
    C = (eval(TempStr[0:-1]) - 32) / 1.8
    print("{:.2f}C".format(C))
elif TempStr[-1] in ['C', 'c']:
    F = 1.8 * eval(TempStr[0:-1]) + 32
    print("{:.2f}F".format(F))
else:
    print("输入格式错误,请重新输入")

3.扩展:支持开尔文温度的三向转换

点击查看代码
def celsius_to_fahrenheit(c):
    return c * 9 / 5 + 32
def fahrenheit_to_celsius(f):
    return (f - 32) * 5 / 9
def celsius_to_kelvin(c):
    return c + 273.15
def kelvin_to_celsius(k):
    return k - 273.15
def fahrenheit_to_kelvin(f):
    return fahrenheit_to_celsius(f) + 273.15
def kelvin_to_fahrenheit(k):
    return celsius_to_fahrenheit(kelvin_to_celsius(k))
def get_input(prompt):
    while True:
        try:
            return float(input(prompt))
        except ValueError:
            print("输入错误,请输入一个数字。")

def main():
    print("温度转换程序")
    print("1. 摄氏温度(C)转华氏温度(F)")
    print("2. 华氏温度(F)转摄氏温度(C)")
    print("3. 摄氏温度(C)转开尔文温度(K)")
    print("4. 开尔文温度(K)转摄氏温度(C)")
    print("5. 华氏温度(F)转开尔文温度(K)")
    print("6. 开尔文温度(K)转华氏温度(F)")
    print("7. 退出")

    while True:
        choice = input("请选择转换类型(1-7):")
        if choice == '7':
            print("退出程序。")
            break
        elif choice in ['1', '2', '3', '4', '5', '6']:
            temp = get_input("请输入温度值:")
            if choice == '1':
                print(f"{temp}°C 等于 {celsius_to_fahrenheit(temp):.2f}°F")
            elif choice == '2':
                print(f"{temp}°F 等于 {fahrenheit_to_celsius(temp):.2f}°C")
            elif choice == '3':
                print(f"{temp}°C 等于 {celsius_to_kelvin(temp):.2f}K")
            elif choice == '4':
                print(f"{temp}K 等于 {kelvin_to_celsius(temp):.2f}°C")
            elif choice == '5':
                print(f"{temp}°F 等于 {fahrenheit_to_kelvin(temp):.2f}K")
            elif choice == '6':
                print(f"{temp}K 等于 {kelvin_to_fahrenheit(temp):.2f}°F")
        else:
            print("无效的选择,请输入1-7之间的数字。")

if __name__ == "__main__":
    main()

posted on 2025-04-18 09:27  encore弥塔  阅读(90)  评论(0)    收藏  举报