Python中BMI计算器if语句无明显原因报错问题排查
BMI计算器单位输入校验错误修复
你的问题出在对Python逻辑运算符和字符串包含判断的误用,导致输入"imperial"时触发错误,具体原因和修复方案如下:
问题根源
or运算符的错误使用:
代码中"metric" or "imperial"的实际效果是返回第一个非空字符串"metric",而非检查输入是否包含两者之一。因此当输入"imperial"时,unit.lower().__contains__("metric")返回False,直接触发第一个错误分支。and运算符的错误使用:"metric" and "imperial"会返回第二个非空字符串"imperial",导致第二个校验逻辑只能检测输入是否包含"imperial",完全无法实现"同时包含两个单位"的校验目的。
修复后的代码
import sys unit_input = input("To begin, please input your units of measurement (Imperial or Metric) ").lower() # 校验:同时输入两个单位的情况 if "metric" in unit_input and "imperial" in unit_input: sys.tracebacklimit = 0 raise Exception("An error has occurred!\n\nPlease check if your unit of measurement is valid/singular") # 校验:输入既非Metric也非Imperial的情况 if "metric" not in unit_input and "imperial" not in unit_input: sys.tracebacklimit = 0 raise Exception("An error has occurred!\n\nPlease check if your unit of measurement is valid/spelled correctly")
关键改进点
- 提前将输入转为小写,避免重复调用
lower(),统一大小写判断逻辑。 - 直接用
in运算符判断字符串包含关系,逻辑更直观清晰。 - 调整校验顺序:先判断"同时包含两个单位"的违规情况,再判断"都不包含"的无效输入情况,逻辑优先级更合理。
内容的提问来源于stack exchange,提问作者lilmonix3
相关产品推荐
相关产品推荐

