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

Python单位转换代码死循环问题排查及优化建议

问题排查与优化方案

核心错误:死循环原因

你的代码陷入死循环是因为while循环的条件逻辑错误:
原代码中while Unit != "L" or "K"的写法等价于(Unit != "L") or True——非空字符串"K"在布尔判断中永远为真,所以不管Unit是什么值,这个条件始终成立,导致循环无法退出。

正确的条件应该是判断Unit既不是"L"也不是"K",可以用两种写法:

  • while Unit != "L" and Unit != "K"
  • while Unit not in ("L", "K")

其他代码问题

  • 拼写错误:变量名wight应为weight,提示语中的valide→valid、charechtar→character,这些细节会影响代码可读性和用户体验。
  • 未处理输入异常:直接用int(wight)转换体重输入,如果用户输入非数字内容(比如字母),程序会直接报错崩溃,需要添加异常捕获逻辑。
  • 大写转换遗漏:仅在第一次输入后执行Unit.upper(),循环内新输入的Unit没有转大写,导致用户输入小写的"l"或"k"时仍会触发循环。

优化后的完整代码

# 获取并验证体重输入
while True:
    try:
        weight = int(input("What is your weight? "))
        break
    except ValueError:
        print("Please enter a valid number for weight.")

# 获取并验证单位输入
while True:
    unit = input("(L) for pounds and (K) for Kilogram: ").upper()
    if unit in ("L", "K"):
        break
    print("Only (L) for pounds and (K) for Kilogram are valid characters.")

# 单位转换与输出
if unit == "L":
    new_weight = weight / 2.2
    print(f"You are {weight} Pounds that is equal to {round(new_weight, 2)} Kilograms")
elif unit == "K":
    new_weight = weight * 2.2
    print(f"You are {weight} Kilograms that is equal to {round(new_weight, 2)} Pounds")

print("the End")

优化说明

  • 拆分体重和单位的输入验证逻辑,分别用循环确保输入合法。
  • 添加try-except捕获体重输入的非数字异常,提升程序健壮性。
  • 将upper()放在单位输入的循环内,确保每次输入都统一转为大写。
  • 用round()限制转换后体重的小数位数,输出更美观。
  • 修正所有拼写错误,提升代码可读性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 14:37:51