You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python单位换算程序无法返回主菜单及代码优化问题求助

问题原因
  • 主菜单的选择变量x仅在循环外赋值一次,循环内部没有重新读取用户主菜单选择的逻辑,所以程序只会一直重复第一次选择的换算类型,无法回到主菜单
  • 原代码中所有子菜单的while循环属于冗余代码,执行一次就主动触发break,没有实际作用
  • 单位换算逻辑错误:千米与英里的换算公式写反,1英里≈1.60934千米,因此公里转英里应为公里数 / 1.60934,英里转公里应为英里数 * 1.60934,原代码计算结果不正确
  • 缩进错误:所有换算函数的缩进层级不符合Python规范,运行会直接报错
  • 没有输入异常处理:用户输入非数字内容时程序会直接崩溃
修正后简化代码
# 英尺转厘米
def f_c():
    foot = float(input('输入英尺数值: '))
    print(f"换算结果: {foot * 30.48} 厘米")

# 厘米转英尺
def c_f():
    cm = float(input('输入厘米数值: '))
    print(f"换算结果: {cm / 30.48} 英尺")

# 公里转英里
def km_mi():
    km = float(input('输入公里数值: '))
    print(f"换算结果: {km / 1.60934} 英里")

# 英里转公里
def mi_km():
    mi = float(input('输入英里数值: '))
    print(f"换算结果: {mi * 1.60934} 公里")

# 摄氏度转华氏度
def ce_fa():
    ce = float(input('输入摄氏度数值: '))
    print(f"换算结果: {(ce * 9/5) + 32} 华氏度")

# 华氏度转摄氏度
def fa_ce():
    fa = float(input('输入华氏度数值: '))
    print(f"换算结果: {(fa - 32) * 5/9} 摄氏度")

if __name__ == "__main__":
    while True:
        # 主菜单
        print("\n===== 单位换算程序 =====")
        print("1. 英尺<->厘米")
        print("2. 公里<->英里")
        print("3. 摄氏度<->华氏度")
        print("4. 退出程序")
        try:
            x = int(input("请选择换算类型: "))
        except ValueError:
            print("输入错误,请输入数字")
            continue
        if x == 4:
            print("程序退出")
            break
        if x not in [1,2,3]:
            print("无效选择,请重新输入")
            continue
        
        # 子菜单
        try:
            if x == 1:
                print("\n1. 英尺转厘米\n2. 厘米转英尺")
                a = int(input("请选择换算方向: "))
                f_c() if a == 1 else c_f()
            elif x == 2:
                print("\n1. 公里转英里\n2. 英里转公里")
                a = int(input("请选择换算方向: "))
                km_mi() if a == 1 else mi_km()
            elif x == 3:
                print("\n1. 摄氏度转华氏度\n2. 华氏度转摄氏度")
                a = int(input("请选择换算方向: "))
                ce_fa() if a == 1 else fa_ce()
        except ValueError:
            print("输入错误,请输入数字")
            continue
        
        # 确认是否继续
        next_cal = input("\n是否继续换算?(yes/no): ").strip().lower()
        if next_cal == "no":
            print("程序退出")
            break
优化点说明
  • 把主菜单逻辑放入最外层循环内,每次换算完成后都会回到主菜单重新选择
  • 增加了输入异常校验,避免用户输入非数字导致程序崩溃
  • 修正了千米和英里的换算公式
  • 简化了冗余的子菜单循环逻辑,去掉了无效代码
  • 增加了退出选项,用户可以主动选择退出或者换算完成后选择是否继续
  • 优化了输入输出提示,更符合中文使用习惯

内容的提问来源于stack exchange,提问作者potato_noodles

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 22:06:02