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 in ["WALK", "RUN", "JOG"]:
if activity == "WALK":
calories_burned_per_minute = burnedWalking(weight)
if activity == "RUN":
calories_burned_per_minute = burnedRunning(weight)
if activity == "JOG":
calories_burned_per_minute = burnedJogging(weight)
if activity not in ["WALK", "JOG", "RUN"]:
activity = input("Invalid input. Will you WALK, RUN, or JOG? ").upper()
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")
每当我尝试运行我的代码时,它说calories_burned_per_minute是未定义的,而我之前已经明确定义了。任何帮助都很感激。谢谢你。
追溯(最近一次调用):文件“",第37行,在NameError中:未定义名称“calories_burned_per_minute”
1条答案
按热度按时间0s7z1bwu1#
引发
NameError
不是bug,这是正确的行为,因为calories_burned_per_minute
确实是未定义的。为什么?因为你的循环没有运行。
''
不是["WALK", "RUN", "JOG"]
的成员。所以activity in ["WALK", "RUN", "JOG"]
是false。您的
while
循环没有运行,因为while
循环只在满足条件时运行,并在不再满足条件时停止。在这里,你的条件永远不会满足。试试这个:
发生了什么?完全没有。
将
while activity in ["WALK", "RUN", "JOG"]
更改为while activity not in ["WALK", "RUN", "JOG"]
那么你获取输入的逻辑是完全错误的。
你应该这样做:
然后这个:
使用
match
case
:你有三个函数,只有一个值是不同的,这是不好的,只是使用一个函数,并通过第二个值作为参数。你的函数名也不遵循Python命名约定,你的变量名也太长了,你没有内联立即返回的变量,你在函数内部使用
print
,你使用input
函数而不是接受参数,你没有做类型提示......我已经重构了你的代码,并删除了所有的cruft:
像这样使用: