You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

燃脂心率与BMI计算器循环异常求助:年龄输入循环无法正常退出

问题排查:燃脂心率与BMI计算器循环异常

我正在开发一款燃脂心率与BMI计算器,要求可处理错误输入并循环请求正确输入,完成后进入下一项输入。计算公式如下:

  • 燃脂心率=(220 - age) * 0.7
  • BMI=703 * lbs / height**2(身高单位为英寸)

我为年龄、身高、体重输入分别编写了while循环,但输入有效年龄后,第一个循环仍持续重复执行。以下是我的代码与作业示例输出:

#Calculate ideal fat burning heart rate and BMI
#(220 - age) * .7 for fat burning heart rate
#BMI = 703 * lbs / height**2 (in)

print("Welcome to the Weber State University Performance Lab!")
print("Please utilize the following calculator to find your ideal fat burning heart rate and BMI.")

#Age entry
while True:
    try: 
        age = float(input("Please enter your age: "))
        if age <= 0:
            raise TypeError ("Please enter a number greater than zero.")
        break
    except ValueError:
            print("Invalid input.")
            print("Please enter your age in numeric format.")
    except TypeError as err:
            print(err)
    except:
            print("Invalid input.")
while True:
    #Height entry
    try: 
        height = float(input("Please enter your height in inches: "))
        if height <= 0:
            raise TypeError ("Please enter a number greater than zero.")
        break
    except ValueError:
            print("Invalid input.")
            print("Please enter your height in inches in numeric format.")
    except TypeError as err:
            print(err)
    except:
            print("Invalid input.")

while True:
    #Weight Entry
    try: 
        weight = float(input("Please enter your weight in pounds: "))
        if weight <= 0:
            raise TypeError ("Please enter a number greater than zero.")
        break
    except ValueError:
            print("Invalid input.")
            print("Please enter your weight in pounds in numeric format.")
    except TypeError as err:
            print(err)
    except:
            print("Invalid input.")

print("Your age:", age, "years old.")
print("Your height:", height, "inches tall.")
print("Your weight", weight, "lbs")

print("Your ideal fat burning heart rate is", float(round((220 - age) * .7)), "BPM.")
print("Your Body Mass Index is", float(round((703 * (weight / height**2)))))

作业示例输出:

Welcome to the Weber State University Human Performance Lab!
Please utilize the following calculator to find your ideal fat burning heart rate and BMI.

Enter age: forty
Invalid age. Must be a number.
Re-enter age: 40
Enter height in inches: hi
Invalid inches value. Must be a number.
Re-enter height in inches: 0
Invalid inches value. Must be positive.
Re-enter height in inches: 69.25
Enter weight in pounds: dog
Invalid pounds value. Must be a number.
Re-enter weight in pounds: -3
Invalid pounds value. Must be positive.
Re-enter weight in pounds: -20
Invalid pounds value. Must be positive.
Re-enter weight in pounds: 150.5

Age = 40
Height = 69.25"
Weight = 150.5 pounds

Fat Burning Heart Rate = 126 bpm
Body Mass Index = 22.1

问题排查与修复

你的代码逻辑本身无语法错误,但存在几个可能导致误解或不规范的问题:

  1. 异常类型误用:你用TypeError处理数值小于等于0的错误,但TypeError是用于处理数据类型不匹配的异常,这类值不符合要求的场景应该用ValueError,虽然不影响功能,但不符合Python异常使用规范。

  2. 提示信息混淆:你的输入提示和错误提示与作业示例不一致,比如示例中错误后会显示Re-enter age:,而你的代码一直用Please enter your age:,可能导致你误以为循环未退出。

  3. 缩进错误(核心排查点):如果输入有效年龄后循环仍重复,最可能的原因是第二个while循环被意外嵌套在第一个循环内部(缩进错误)。请检查代码缩进,确保三个while循环是同级独立的。

修复后的代码

以下是调整后的代码,修复了异常类型,同步了示例提示信息,确保逻辑正确:

# Calculate ideal fat burning heart rate and BMI
# (220 - age) * .7 for fat burning heart rate
# BMI = 703 * lbs / height**2 (in)

print("Welcome to the Weber State University Human Performance Lab!")
print("Please utilize the following calculator to find your ideal fat burning heart rate and BMI.\n")

# Age entry
while True:
    try:
        age = float(input("Enter age: "))
        if age <= 0:
            raise ValueError("Invalid age. Must be positive.")
        break
    except ValueError as err:
        if "could not convert string to float" in str(err):
            print("Invalid age. Must be a number.")
        else:
            print(err)
        age = input("Re-enter age: ")
        continue

# Height entry
while True:
    try:
        height = float(input("Enter height in inches: "))
        if height <= 0:
            raise ValueError("Invalid inches value. Must be positive.")
        break
    except ValueError as err:
        if "could not convert string to float" in str(err):
            print("Invalid inches value. Must be a number.")
        else:
            print(err)
        height = input("Re-enter height in inches: ")
        continue

# Weight Entry
while True:
    try:
        weight = float(input("Enter weight in pounds: "))
        if weight <= 0:
            raise ValueError("Invalid pounds value. Must be positive.")
        break
    except ValueError as err:
        if "could not convert string to float" in str(err):
            print("Invalid pounds value. Must be a number.")
        else:
            print(err)
        weight = input("Re-enter weight in pounds: ")
        continue

print(f"\nAge = {age}")
print(f"Height = {height}\"")
print(f"Weight = {weight} pounds\n")

fat_burning_hr = round((220 - age) * 0.7, 1)
bmi = round(703 * weight / (height ** 2), 1)

print(f"Fat Burning Heart Rate = {fat_burning_hr} bpm")
print(f"Body Mass Index = {bmi}")

关键修复点

  • 用ValueError替代TypeError处理数值无效的情况,符合Python异常规范。
  • 调整提示信息与作业示例完全一致,避免混淆循环阶段。
  • 优化错误判断,区分“非数字输入”和“数值非正”的不同提示。
  • 使用f-string格式化输出,让结果更简洁易读。

内容的提问来源于stack exchange,提问作者Stephanie Davi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 04:07:10