类型错误:不支持的操作数类型(一个或多个)为:“浮动”和“浮动”(TypeError: unsupp

2019-06-23 19:21发布

我写了这个简单的程序来计算一个人的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" 

OUTPUT

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'

我要去哪里错了? 任何人都只是让我知道..

谢谢 :)。

Answer 1:

&是位运算符 ,我认为你正在寻找布尔and

但是请注意,Python也支持的语法如下:

if 18.5 < bmi1 < 24.9:
    # ...

既然你似乎已经缩进trobled这是你的脚本可能什么样子:

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值,所以没有必要写两次同样的事情。

剩下的东西做,整个脚本可能会封装成函数:)



文章来源: TypeError: unsupported operand type(s) for &: 'float' and 'float'