2015-08-28 47 views
0

我是一个新手,Python和最近已试图创建一个BMI计算器,但我用下面的代码有错误:的Python:的raw_input和不支持的操作类型

def calculator(): 

    weight = raw_input('Please enter your weight (kg):') 

    if weight.isdigit and weight > 0: 
     height = raw_input('Please enter your height (m):') 

     if height.isdigit and height > 0: 
      bmi = (weight)/(height ** 2) 

      print "Your BMI is", bmi 

      if bmi < 18.5: 
       print 'You are underweight.' 
      if bmi >= 18.5 and bmi < 25: 
       print 'Your BMI is normal.' 
      if bmi >= 25 and bmi < 30: 
       print 'You are overweight.' 
      if bmi >= 30: 
       print 'You are obese.'  

     else: 
      height = raw_input('Please state a valid number (m):') 


    else: 
     weight = raw_input('Please state a valid number (kg):') 

每当我试着要执行的代码,我能够进入的体重和身高,但我则与此错误消息面对:

Traceback (most recent call last): 
    File "*location*", line 40, in <module> 
    calculator() 
    File "*location*", line 15, in calculator 
    bmi = (weight)/(height ** 2) 
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int' 

我这个愚蠢的问题和错误缠身代码道歉,但我很新的编程并欣赏任何形式的帮助。 :)

+1

你从'raw_input'得到的东西总是在字符串类型中用int() ' – The6thSense

+1

请注意,'weight.isdigit'只引用方法,它实际上不会调用*方法。 –

+0

你的程序中有很多错误只是通过python的基础,然后再试一次,你在这里试图完成什么'如果高度==退出:' – The6thSense

回答

2

raw_input始终返回str对象。您需要明确地将输入转换为int。 您可以做

val = int(raw_input(...)) 

val = raw_input(...) 
val = int(val) 

正如其他人所提到的,在你的代码中的许多错误。这里是一个:

if height == exit: 

weight相同的问题条件。我只是想指出,因为你没有问这个问题,所以我会让你找出问题是什么:)。

2

请使用这种方式

def calculator(): 

    weight = int(raw_input('Please enter your weight (kg):')) 

    if weight >0 and weight > 0: 
     height = int(raw_input('Please enter your height (m):')) 

     if height >0 and height > 0: 
      bmi = (weight)/(height ** 2) 

      print "Your BMI is", bmi 

      if bmi < 18.5: 
       print 'You are underweight.' 
      if bmi >= 18.5 and bmi < 25: 
       print 'Your BMI is normal.' 
      if bmi >= 25 and bmi < 30: 
       print 'You are overweight.' 
      if bmi >= 30: 
       print 'You are obese.'  

     else: 
      height = int(raw_input('Please state a valid number (m):')) 
     if height == exit: 
      exit() 

    else: 
     weight = int(raw_input('Please state a valid number (kg):')) 

    if weight == exit: 
     exit() 

你需要转换的输入项为int,因为它们都是字符串。

而且你不再需要检查它是否是一个数字,

不过,我建议你添加另一个条件,如:

if weight and height: 
    #Do stuff 

如果没有提供任何条目。

编辑:!

/\如果你需要小数扮演他们漂浮

1

进入应转换为浮动号码。只需更改 bmi = float(weight)/(float(height)** 2) 你很好走

相关问题