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

Python循环实践问题:跳出两层循环及输入顺序异常修复

BMI计算器问题修复方案

问题说明

  • 自学编程新手,编写BMI计算器时遇到两个问题:
    1. 不知道如何在Python中跳出两层循环(对应原代码第60行)
    2. 输入有效数据并选择添加他人信息时,程序先询问体重(weight)而非身高(height)

原代码如下:

CONVERSION_FACTOR = 703
YES="YES , yes"
NO="NO , no"

print("")
print("Hello, and Welcome to the BMI Calculator, please follow the instructions and input numeric values only!")

while True:

 try:
    height:float = float(input("Please enter the person's height in inches:  "))
    isvalid = True
 except:
    isvalid =False

 if not isvalid:
    print("that input is not vaild please enter the person's height as a numeric value only!.")
    continue
 else:
 
  if 20 <= height and height <= 120:

    while True:
      try:
        weight:float = float(input("Please enter the person's weight in pounds:  "))
        isvalid = True
      except:
          isvalid =False
     
      if not isvalid:
          print("that input is not vaild please enter the person's weight as a numeric value!")
          continue
      else:
       
        if 10 <= weight <=400:
            Bmi = weight / (height ** 2) * CONVERSION_FACTOR
            stop_weight = weight * 0.85
            for i in range(0, 100):
                if  Bmi < 16:  
                 category = "severely underweight"
                elif 16 <= Bmi < 18.5:
                 category = "underweight"
                elif 18.5 <= Bmi < 25:
                 category = "healthy"
                elif 25 <= Bmi <= 30:  
                 category = "overweight"
                else:
                 category = "obese"

                if weight < stop_weight:
                  break
                print("The BMI for a", + float(round(height,1)), "inches tall person who weighs", + float(round(weight,1)), "lbs. is",
                          + float(round(Bmi, 1)))
                print("which is categorized as " + category)
                percent_weight = round(weight * 0.05,1)
                weight = weight - percent_weight
                
        else:
            print("Please enter a weight of at least 10 pounds and no more than 400 lbs")
            continue

        while True:
            resume = input(str("would you like to input data for another person? Please only input YES or NO "))
            if resume == "YES":
                break
            if resume=="yes":
                break
            if resume == "NO":
                print("thank you have a nice day!")
                exit()
            if resume=="no":
                print("thank you have a nice day!")
                exit()
            else:
                print("You have entered an invalid input please try again")
            continue
  else:
    print("Please enter the height between 20 and 120 inches")
    continue      

修复方案

问题1:跳出两层循环

用标志变量控制外层循环的退出:在体重输入的while循环前定义exit_weight_loop = False,当for循环触发break时,把exit_weight_loop设为True,然后在体重循环里检查这个变量,满足就跳出外层循环。

问题2:回到身高输入流程

调整询问是否继续的代码缩进,将其移到身高验证的if块末尾(体重循环之外),这样当用户选择YES时,会回到最外层的身高输入循环,重新询问身高。

修改后的完整代码

CONVERSION_FACTOR = 703

print("")
print("Hello, and Welcome to the BMI Calculator, please follow the instructions and input numeric values only!")

while True:
    # 身高输入验证
    try:
        height: float = float(input("Please enter the person's height in inches:  "))
        isvalid = True
    except:
        isvalid = False

    if not isvalid:
        print("That input is not valid please enter the person's height as a numeric value only!.")
        continue
    
    if not (20 <= height <= 120):
        print("Please enter the height between 20 and 120 inches")
        continue

    # 体重输入循环
    exit_weight_loop = False
    while not exit_weight_loop:
        try:
            weight: float = float(input("Please enter the person's weight in pounds:  "))
            isvalid = True
        except:
            isvalid = False
        
        if not isvalid:
            print("That input is not valid please enter the person's weight as a numeric value!")
            continue
        
        if not (10 <= weight <= 400):
            print("Please enter a weight of at least 10 pounds and no more than 400 lbs")
            continue

        # 计算并打印BMI变化
        stop_weight = weight * 0.85
        for i in range(0, 100):
            # 计算当前BMI和分类
            bmi = weight / (height ** 2) * CONVERSION_FACTOR
            if bmi < 16:  
                category = "severely underweight"
            elif 16 <= bmi < 18.5:
                category = "underweight"
            elif 18.5 <= bmi < 25:
                category = "healthy"
            elif 25 <= bmi <= 30:  
                category = "overweight"
            else:
                category = "obese"

            if weight < stop_weight:
                exit_weight_loop = True  # 标记要跳出体重循环
                break
            
            print(f"The BMI for a {round(height,1)} inches tall person who weighs {round(weight,1)} lbs. is {round(bmi, 1)}")
            print(f"which is categorized as {category}")
            percent_weight = round(weight * 0.05, 1)
            weight -= percent_weight

    # 询问是否继续(缩进调整到这里,回到身高循环)
    while True:
        resume = input("Would you like to input data for another person? Please only input YES or NO ")
        resume = resume.strip().upper()
        if resume == "YES":
            break
        elif resume == "NO":
            print("Thank you have a nice day!")
            exit()
        else:
            print("You have entered an invalid input please try again")

额外优化说明

  • 简化了YES/NO的判断逻辑,用strip().upper()统一转为大写,减少重复判断
  • 修正了变量名(Bmi改为bmi,符合Python命名规范)
  • 用f-string优化了打印语句,更简洁易读
  • 调整了缩进结构,让代码逻辑更清晰

内容的提问来源于stack exchange,提问作者Cole Carley

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 19:01:19