Python BMI计算函数compute_bmi无法通过测试,请求错误排查
BMI计算函数问题修正
核心错误点
compute_bmi函数未定义参数,依赖全局变量height和weight,完全不符合测试用例的调用逻辑(测试用例调用的是check_bmi并传入参数列表)- 输入读取、有效性校验写在函数外部,无法适配测试用例的传参方式
- 异常处理逻辑位置错误,无法覆盖参数转换时的异常场景
适配测试用例的修正代码
结合任务要求和测试用例的调用规则,修正后的代码如下:
def compute_bmi(height, weight): bmi = weight / (height ** 2) if bmi < 18.5: return "Under" elif 18.5 <= bmi < 25: return "Normal" elif 25 <= bmi < 35: return "Over" else: return "Obese" def check_bmi(params): try: height = float(params[0]) weight = float(params[1]) if height <= 0 or weight <= 0: return "Please enter a valid number." return compute_bmi(height, weight) except (ValueError, IndexError): return "Please enter a valid number." # 保留原本地交互逻辑(仅在直接运行脚本时生效) if __name__ == "__main__": try: height = float(input("Enter height in m: ")) weight = float(input("Enter weight in kg: ")) if height <= 0 or weight <= 0: print("Please enter a valid number.") else: print(compute_bmi(height, weight)) except ValueError: print("Please enter a valid number.")
修正说明
- 将
compute_bmi改为接收height和weight参数,遵循函数封装规范,不再依赖全局变量 - 新增
check_bmi函数适配测试用例:接收参数列表,内部完成类型转换、有效性校验和异常捕获 - 把异常处理移至
check_bmi内部,覆盖参数转换失败、参数数量不足的场景 - 原有的用户交互逻辑被放在
if __name__ == "__main__"块中,不影响测试用例的调用
内容的提问来源于stack exchange,提问作者programming_is_fun
相关产品推荐
相关产品推荐

