Python代码报错NameError:已定义的calories_burned_per_minute提示未定义
问题排查与代码修正
核心错误分析
- 语法错误:所有变量赋值语句末尾的多余句号(比如
weight = float(input(...)).),这会直接导致Python解析失败。 - 循环逻辑颠倒:初始
activity为空字符串,原循环条件while activity in ["WALK", "RUN", "JOG"]意味着只有当activity是合法值时才进入循环,但初始值不满足条件,循环完全不执行,导致calories_burned_per_minute从未被赋值,后续计算触发NameError。 - 输入验证逻辑混乱:原代码在循环内的判断顺序错误,无法有效引导用户输入合法选项。
修正后的完整代码
def standardCalBurn(weight, height, age): calories_needed = 655 + (4.3 * weight) + (4.7 * height) - (4.7 * age) print(f"{calories_needed:.1f} calories are needed per day to sustain weight of {weight}") def burnedRunning(weight): calories_burned_per_minute = weight * 0.095 return calories_burned_per_minute def burnedWalking(weight): calories_burned_per_minute = weight * 0.054 return calories_burned_per_minute def burnedJogging(weight): calories_burned_per_minute = weight * 0.0775 return calories_burned_per_minute # 移除赋值语句末尾的多余句号 weight = float(input("Please enter your weight: ")) height = float(input("Please enter your height (in inches): ")) age = float(input("Please enter your age: ")) standardCalBurn(weight, height, age) calories_to_burn = float(input("How many calories do you wish to burn while exercising? ")) # 重构循环:持续获取输入直到用户提供合法选项 activity = "" while activity not in ["WALK", "RUN", "JOG"]: activity = input("Will you WALK, RUN, or JOG? ").upper() if activity not in ["WALK", "RUN", "JOG"]: print("Invalid input. Please try again.") # 根据合法的活动类型计算卡路里消耗 if activity == "WALK": calories_burned_per_minute = burnedWalking(weight) elif activity == "RUN": calories_burned_per_minute = burnedRunning(weight) elif activity == "JOG": calories_burned_per_minute = burnedJogging(weight) minutes_to_burn = calories_to_burn / calories_burned_per_minute print(f"You will burn {calories_burned_per_minute:.2f} calories per minute") print(f"You will need to {activity} for {minutes_to_burn:.2f} minutes")
关键修改说明
- 去掉所有变量赋值末尾的句号,修复基础语法错误。
- 反转循环条件为
while activity not in ["WALK", "RUN", "JOG"],确保用户输入不合法时重复提示,直到输入正确选项。 - 将活动判断移到循环之后,保证
calories_burned_per_minute一定会被赋值,避免NameError。 - 使用
elif替代多个独立if,减少不必要的条件判断,提升代码效率。
内容的提问来源于stack exchange,提问作者Spencer
相关产品推荐
相关产品推荐

