首页 > 解决方案 > 循环不执行时,defhealthindex 函数不发生

问题描述

我无法让 healthindex 功能正常工作。即使我输入 b 或 h,while 循环也不会执行。我试图做到这一点,以便输入会根据输入产生两个单独的代码段,但这并没有发生。谢谢!

def inputM():
  print("Enter weight in kg")
  weightm = float(input())
  print("Enter heigh in meters")
  heightm = float(input())
  return weightm, heightm
def inputI():
  print("Enter weight in pounds")
  weighti = float(input())
  print("Enter height in inches")
  heighti = float(input())
  return weighti, heighti

def healthindex (BMIList, BMINum, bmi):
  if healthy == "b": 
    print (str(bmi))
  elif healthy == "h":
    index = 0
    print ("Your bmi is" + (str(bmi))
    while index < len(BMIList):
      if bmi < BMINum[index]:
        print ("And, you are " + BMIList[index])
        return
      index = index + 1
    print("You are Obese")
  return

BMIList = ["severly underweight", "underweight", "healthy", "overweight", "obese"]
BMINum = [12, 18.4, 24.9, 29.9, 200]
print("Welcome to BMI Calculator!")
print("Enter I for Imperial or M for Metric")
request = input().upper()

if request == "M":
  weightm, heightm = inputM()
  bmi = weightm/(heightm**2)
elif request == "I":
  weighti, heighti = inputI()
  bmi = (703*weighti)/(heighti**2)  
else:
  print("Invalid input")

print("Enter b to only see your bmi or enter h if you would like to see your bmi and health index")

healthy= input()
healthindex (BMIList, BMINum, bmi)

标签: python

解决方案


您还应该将健康变量传递给 healthindex 函数

healthindex (BMIList, BMINum, bmi, healthy)

完整代码

def inputM():
  print("Enter weight in kg")
  weightm = float(input())
  print("Enter heigh in meters")
  heightm = float(input())
  return weightm, heightm
def inputI():
  print("Enter weight in pounds")
  weighti = float(input())
  print("Enter height in inches")
  heighti = float(input())
  return weighti, heighti

def healthindex (BMIList, BMINum, bmi, healthy):
  if healthy == "b": 
    print (str(bmi))
  elif healthy == "h":
    index = 0
    print ("Your bmi is " + (str(bmi)))
    while index < len(BMIList):
      if bmi < BMINum[index]:
        print ("And, you are " + BMIList[index])
        return
      index = index + 1
    print("You are Obese")
  return

BMIList = ["severly underweight", "underweight", "healthy", "overweight", "obese"]
BMINum = [12, 18.4, 24.9, 29.9, 200]
print("Welcome to BMI Calculator!")
print("Enter I for Imperial or M for Metric")
request = input().upper()

if request == "M":
  weightm, heightm = inputM()
  bmi = weightm/(heightm**2)
elif request == "I":
  weighti, heighti = inputI()
  bmi = (703*weighti)/(heighti**2)  
else:
  print("Invalid input")

print("Enter b to only see your bmi or enter h if you would like to see your bmi and health index")

healthy= input()
healthindex (BMIList, BMINum, bmi, healthy)

推荐阅读