/ /このPython BMI計算機を修正するには? - python、デバッグ

このPython BMI計算機を修正するには? - Python、デバッグ

これは私がpythonで書いたBMI計算機です

print("BMI calculator V1")

name = str(input("What"s your name?"))
weight = int(input("Your weight in Kilograms"))
height = float(input("Your height in Metres"))

def function(w, h):    #function here is the bmi calculator
bmi = w / h ** 2
return("Your BMI is " + str(bmi))

bmi_user = function(weight, height)
print(bmi_user)

if bmi_user < 18:
print(name + "," + "you are underweight")
elif bmi_user > 25:
print(name + "," + "you are overweight")
else:
print(name + "," + "you are normal")

コードを実行すると、次のエラーが表示されます。

15行目 float(bmi_user)<18の場合
ValueError:文字列をfloatに変換できませんでした。

回答:

回答№1は1

エラーメッセージは明らかです。文字列とdoubleの間の比較はできません。

あなたの関数が返すものを見てください:文字列。

def function(w, h):    #function here is the bmi calculator
bmi = w / h ** 2
return("Your BMI is " + str(bmi))

bmi_user = function(weight, height)

これでうまくいくでしょう。

def bmi_calculator(w, h):
return w / h ** 2

回答№2の場合は1

計算から文​​字列を返さないようにして修正してください。あなたはこれを与えるべきです 小さなプログラムをデバッグする方法(#1) コードをデバッグするために読んでそれに従ってください。

print("BMI calculator V1")

name = str(input("What"s your name?"))
weight = int(input("Your weight in Kilograms"))
height = float(input("Your height in Metres"))

def calcBmi(w, h):    # function here is the bmi calculator
bmi = w / h ** 2
return bmi        # return a float, not a string

bmi_user = calcBmi(weight, height)  # now a float
print(f"Your BMI is: {bmi_user:.2f}")   # your output message

if bmi_user < 18:
print(name + "," + "you are underweight")
elif bmi_user > 25:
print(name + "," + "you are overweight")
else:
print(name + "," + "you are normal")

function 本当に良い名前ではありません、私はそれをに変更しました calcBmi.


回答№3の場合は0

あなたの関数def function(w、h):以下のように文字列を返します。

return("Your BMI is " + str(bmi))

これは、下記のようにあなたのステートメントで指定された整数と比較することはできません。

if bmi_user < 18:

下の行もエラーになります

elif bmi_user > 25:

下記のように機能を変更してください、それは働きます

def function(w, h):    #function here is the bmi calculator
bmi = w / h ** 2
return bmi