TypeError: unsupported operand type(s) for &: 'float' and 'float'

匿名 (未验证) 提交于 2019-12-03 10:03:01

问题:

I wrote this simple program to calculate one's BMI. But I am unable to execute it complete. Below is my program,

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 & bmi1  25 & 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 bmi218.5 & bmi225 & 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 "", line 1, in    File "bmi.py", line 11, in      if bmi1 > 18.5 & bmi1 

Where am I going wrong? Anyone just let me know..

Thanks :).

回答1:

& is a bitwise operator, I think you were looking for the boolean and.

But notice that Python also supports the following syntax:

if 18.5 

Since you seemed to have trobled with indentation this is how your script might look like:

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 = 30:     print "Your are obese" 

There are a couple of slight improvements:

  • The explicit conversion (since in Python 3 the input function behave like raw_input and there's nothing like the Python 2 input, it might be a good habit to write your input like that)
  • What really changes is the bmi value, so there's no need to write two times the same thing.

Something left to do, might be wrap the whole script into functions :)



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!