如何编写代码处理BMI计算器的输入错误?修复体重输入异常问题
修复Python BMI计算器的输入错误处理问题
你的问题出在BMI函数的输入逻辑上:身高和体重的输入被放在同一个try块里,外层套了while True循环。一旦体重输入无效触发ValueError,整个循环会从头执行,导致重新要求输入身高,而不是重新输入体重。
下面是修正后的代码:
def mainMenu(): print("1. Calculate body mass index (BMI).") print("2. View membership cost.") print("3. Exit the program.") while True: try: choice = int(input("Enter your choice: ")) if choice == 1: BMI() break elif choice == 2: Membership() break elif choice == 3: break else: print("Incorrect choice. Enter 1-3") except ValueError: print("Invalid choice. Enter 1-3") def BMI(): # 单独处理身高输入,确保输入有效 while True: try: h = float(input("Enter your height in meters: ")) if h <= 0: print("Height must be a positive number. Try again.") continue break except ValueError: print("Invalid height. Enter a numeric value. Try again.") # 单独处理体重输入,确保输入有效 while True: try: w = float(input("Enter your weight in kg: ")) if w <= 0: print("Weight must be a positive number. Try again.") continue break except ValueError: print("Invalid weight. Enter a numeric value. Try again.") # 计算并输出BMI结果 bmi_value = w / (h * h) print("BMI Calculated is: ", bmi_value) if bmi_value < 18.5: print("Underweight") elif 18.5 <= bmi_value < 25: print("Normal") elif 25 <= bmi_value < 30: print("Overweight") elif bmi_value >= 30: print("Obese") # 补充未实现的Membership函数,避免运行报错 def Membership(): print("Membership cost feature is not implemented yet.") mainMenu()
关键修改说明:
- 把身高和体重的输入拆分成两个独立循环,每个输入单独处理异常,确保某一项输入出错时,只重新要求输入该项
- 添加了身高、体重的合理性判断(必须大于0),提升程序健壮性
- 修正原代码中
mainMenu函数里错误的mainMenu调用(缺少括号) - 移除原BMI函数中多余的
else分支(原逻辑会导致正常BMI范围也输出错误提示) - 重命名
BMI变量为bmi_value,避免和函数名冲突
内容的提问来源于stack exchange,提问作者Natalie Greg Enderby
相关产品推荐
相关产品推荐

