所以我现在正在学习Python,我编写了以下代码来练习:
import time
from decimal import Decimal
name = input("\nPlease enter your name: ")
def bmi(weight, height):
bmi = weight/(height**2)
if bmi > 29.9:
report = "obese"
elif bmi <= 29.9 and bmi > 24.9:
report = "overweight"
elif bmi <= 24.9 and bmi > 18.5:
report = "normal"
elif bmi <= 18.5:
report = "underweight"
else:
report = "to be lying"
return (bmi, report)
while True:
weight = Decimal(input("\nEnter your weight (kg): "))
if weight == 0:
print("You can't have a weight of 0. Try again!")
continue
if weight < 0:
print("A negative weight? Really?")
continue
height = Decimal(input("Enter your height (cm): "))
height = height/100
bmi, report = bmi(weight, height)
bmi = round(bmi, 1)
time.sleep(1)
print("\n" + name.title() + ", according to your BMI (" + str(bmi) +
"), you are considered " + report + ".")
qprompt = input("\nDo you wish to quit? (y/n): ")
if qprompt == 'y':
break
else:
continue
在while循环再次开始并且我输入了一个权重和高度之后,这段代码似乎返回了一个错误。它第一次运行良好,但在我告诉它继续运行,然后输入重量和高度后,它崩溃并给出以下错误:
^{pr2}$我想我应该在这里寻求帮助,因为我无法解决问题。 谢谢!在
您使用符号
bmi
的方式不明确。在当您执行
bmi, report = bmi(weight, height)
操作时,实际上会重写此符号作为对同名函数的引用。在所以在第一次迭代中它引用了一个函数,但是在第二次迭代中它引用了一个(不可调用的)变量。在
因此,运行时解释语言的优势是对您不利的。在
你在写作
使
^{pr2}$bmi
成为一个数字。在循环的下一次迭代中,您将编写把它当作一个函数。在
决定
bmi
是否是结果函数的名称,并始终使用它相关问题 更多 >
编程相关推荐