我写了这个简单的程序来计算一个人的BMI。但我无法完成它。以下是我的计划,
PROGRAM
h = input("Please Enter your height in meters:")
q = raw_input("Do you want to enter your weight in kg or lbs?")
if q=="kg":
w1 = input("Please Enter your weight in kgs:")
bmi1 = w1/(h*h)
print "Your BMI is", bmi1
if bmi1 <= 18.5:
print "Your are underweight."
if bmi1 > 18.5 & bmi1 < 24.9:
print "Your weight is normal."
if bmi1 > 25 & bmi1 < 29.9:
print "Your are overweight"
if bmi1 >= 30:
print "Your are obese"
if q=="lbs":
w2 = input("Please Enter your weightin lbs:")
bmi2 = w2/((h*h)*(39.37*39.37)*703)
print "Your BMI is:", bmi2
if bmi2<= 18.5:
print "Your are underweight."
if bmi2>18.5 & bmi2<24.9:
print "Your weight is normal."
if bmi2>25 & bmi2<29.9:
print "Your are overweight"
if bmi2>=30:
print "Your are obese"
输出
Please Enter your height in meters:1.52
Do you want to enter your weight in kg or lbs?kg
Please Enter your weight in kgs:51
Your BMI is 22.074099723
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "bmi.py", line 11, in <module>
if bmi1 > 18.5 & bmi1 < 24.9:
TypeError: unsupported operand type(s) for &: 'float' and 'float'
我哪里错了?任何人都让我知道..
谢谢:)。
答案 0 :(得分:8)
&
是bitwise operator,我认为您正在寻找布尔值and
。
但请注意,Python还支持以下语法:
if 18.5 < bmi1 < 24.9:
# ...
由于您似乎已经缩减了缩进,因此您的脚本可能如下所示:
h = raw_input("Please enter your height in meters: ")
h = float(h)
w_unit = raw_input("Do you want to enter your weight in kg or lbs? ")
w = raw_input("Please enter your weight in {}: ".format(w_unit))
w = int(w)
if w_unit == "kg":
bmi = w / (h*h)
elif w_unit == "lbs":
bmi = w / ((h*h) * (39.37 * 39.37) * 703)
print "Your BMI is {:.2f}".format(bmi)
if bmi <= 18.5:
print "Your are underweight."
elif 18.5 < bmi <= 25:
print "Your weight is normal."
elif 25 < bmi < 30:
print "Your are overweight"
elif bmi >= 30:
print "Your are obese"
有一些小的改进:
input
函数的行为类似于raw_input
,并且没有像Python 2 input
那样的东西,所以编写输入可能是个好习惯)bmi
值,所以不需要写两次相同的东西。剩下的事情可能是将整个脚本包装成函数:)