/ / Comment réparer cette calculatrice Python BMI? - Python, débogage

Comment réparer cette calculatrice Python BMI? - Python, débogage

Ceci est une calculatrice d'IMC que j'ai écrit en python

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")

Il montre l'erreur suivante lorsque je lance le code

ligne 15, dans si float (bmi_user) <18:
ValueError: impossible de convertir la chaîne en float:

Réponses:

1 pour la réponse № 1

Le message d'erreur est clair: vous ne pouvez pas faire de comparaisons entre une chaîne et un double.

Regardez ce que votre fonction retourne: une chaîne.

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)

Vous ferez mieux avec ceci:

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

1 pour la réponse № 2

Corrigez-le en ne renvoyant pas une chaîne de votre calcul. Tu devrais donner ça Comment déboguer de petits programmes (# 1) une lecture et suivez-le pour déboguer votre code.

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 n'est pas un très bon nom, je l'ai changé pour calcBmi.


0 pour la réponse № 3

Votre fonction def fonction (w, h): renvoie une chaîne comme ci-dessous.

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

Cela ne peut pas être comparé à un entier tel que spécifié dans vos instructions, comme ci-dessous.

if bmi_user < 18:

La ligne ci-dessous sera également une erreur

elif bmi_user > 25:

Modifiez votre fonction comme ci-dessous, cela fonctionnera

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