BMI计算器:值错误:无法将字符串转换为浮点值:X

2024-06-10 07:00:07 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我决定学习Python上的代码,因为我有C++和C语言的经验,老实说,对我来说什么都不是。另一方面,Python则是如此。我决定做一个体重指数计算器,因为我发现它很容易。问题出现在if部分。我添加了找到的代码,但它只是将一个错误切换到另一个错误。任何提示将不胜感激:)

旁注:这只是一个更大代码的一部分,它告诉你应该摄入多少克脂肪。但现在我被困在这里

    try:
        weight = float(input("""What is your weight (Kg)?
                           >>> """))

        height = float(input("""What your height (m)?
                            >>> """))
    except ValueError:
        print("Incorrect input")
        continue
    bmi = weight / (height * height), 2

    print(name + " your BMI is " + str(bmi))

    bmi2 = float('.'.join(str(ele) for ele in bmi))
    if bmi2 < 18.4:
        print("You are under weight by BMI standards!")
    elif bmi2 == 18.5 and bmi2 <= 24.9:
        print("You are normal weight by BMI standards!")
    elif bmi2 == 25 and bmi2 <= 29.9:
        print("You are over weight by BMI standards!")
    elif bmi2 == 30 and bmi2 <= 34.9:
        print("You have obesity (class 1) by BMI standards!")
    elif bmi2 == 35 and bmi2 <= 39.9:
        print("You have obesity (class 2) by BMI standards!")
    elif bmi2 > 40:
        print("You have obesity (class 3) by BMI standards!")

Tags: and代码youinputyourbyfloatprint
1条回答
网友
1楼 · 发布于 2024-06-10 07:00:07

您的代码有一些问题,让我们来看看:

  1. 在第9行,您有一个非法的continue语句。您没有处于循环或switch
  2. 在第11行(编辑前12行),您使用了一个名为name的变量。我猜您是在提供的代码之外定义的,但是如果不是,您必须定义它
  3. 您将BMI输出为tuple。这可以追溯到第9行(编辑前的第10行),在那里您将其定义为weight / (height * height), 2。移除, 2
  4. 我不知道您使用第13行定义的变量bmi2试图做什么,您只需在这些函数中使用bmi,就可以正常工作
  5. 您还需要将关于BMI标准部分中的所有==运算符更改为>;=,以及andorand语句

相关问题 更多 >