2013-08-16 156 views
-1
print("Please enter your Weight") 
weight = input(">") 
print("Please enter your height") 
height = input(">") 
bmi = weight/height 
if int(bmi) <= 18: 
print("you are currently under weight") 
elif int(bmi)>=24: 
print("you are normal weight") 
else: 
print("you are over weight") 

回溯不受支持的操作數類型(個),/: 'STR' 和 'STR'

File "C:\Users\reazonsraj\Desktop\123.py", line 6, in <module> 
bmi = weight/height 
TypeError: unsupported operand type(s) for /: 'str' and 'str' 
+0

你輸入一個字符串,然後試圖把它與一個字符串分割,你的輸入轉換爲一個int –

+1

使用'int':'INT(重量)/ INT(高度)' –

+4

順便說一下,這不是你計算BMI的方法。 – JJJ

回答

1

當輸入它保存爲一個字符串數據。你需要做的是將其轉換爲int。

print("Please enter your Weight") 
weight = int(input(">")) 
print("Please enter your height") 
height = int(input(">")) 
bmi = weight/height 
if int(bmi) <= 18: 
print("you are currently under weight") 
elif int(bmi)>=24: 
print("you are normal weight") 
else: 
print("you are over weight") 

這將解決一個問題,但它不能解決所有問題。如果您要輸入十進制數,那麼您將收到ValueError,因爲int()涉及整數。要解決此問題,您將需要使用float()而不是int。

print("Please enter your Weight") 
weight = float(input(">")) 
print("Please enter your height") 
height = float(input(">")) 
bmi = weight/height 
+0

但是當我輸入高度爲5.5它顯示此錯誤 ValueError:無效的文字爲int()與基地10:'5.5' –

1
def enter_params(name): 
    print("Please enter your {}".format(name)) 
    try: 
     return int(input(">")) 
    except ValueError: 
     raise TypeError("Enter valid {}".format(name)) 
height = enter_params('height') 
weight = enter_params('weight') 
bmi = int(weight/height) 
if bmi <= 18: 
    print("you are currently under weight") 
elif bmi >= 24: 
    print("you are normal weight") 
else: 
    print("you are over weight") 
1
print("Please enter your Weight") 
weight = float(input()) 
print("Please enter your height") 
height = float(input()) 
bmi = weight/height 
if (bmi) <= 18: 
print("you are currently under weight") 
elif (bmi)>=24: 
print("you are normal weight") 
else: 
print("you are over weight") 
+0

感謝一羣人剛剛解決它,並得到正確的方法來做BMI以及:) –

相關問題