gpt4 book ai didi

python - 类型错误 : unsupported operand type(s) for &: 'float' and 'float'

转载 作者:行者123 更新时间:2023-11-28 20:09:42 25 4
gpt4 key购买 nike

我编写了这个简单的程序来计算一个人的 BMI。但是我无法完整地执行它。下面是我的程序,

程序

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'

我哪里错了?谁让我知道..

谢谢 :).

最佳答案

&bitwise operator ,我认为您正在寻找 bool 值 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"

有一些小的改进:

  • 显式转换(因为在 Python 3 中,input 函数的行为类似于 raw_input,而 Python 2 中的 input 完全不同,它可能是像这样写你的输入的好习惯)
  • 真正改变的是 bmi 值,所以没有必要写两次相同的东西。

还有一些事情要做,可能是将整个脚本包装到函数中:)

关于python - 类型错误 : unsupported operand type(s) for &: 'float' and 'float' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10246418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com