如果要正确处理0数字,方法之一是在输入0时引发异常:#Function for calculating BMI
def bmi_calculator():
flag='yes'
while flag != 'no':
print ("\n BMI Calculator")
#Exception block for catching non integer inputs
try:
#Prompting user to input weight
weight = int(input('Enter your weight in pounds : '))
if weight == 0:
raise ValueError
except ValueError:
print ('Oops!! Kindly enter non-zero numbers only.')
flag = input('Do you want to try again? yes/no : ')
continue
try:
#Prompting user to input height
height = float(input('Enter your height in inches : '))
if height == 0:
raise ValueError
except ValueError:
print ('Oops!! Kindly enter non-zero numbers only.')
flag = input('Do you want to try again? yes/no : ')
continue
#Formula for calculating BMI
BMI = round(weight * 703/(height*height), 2)
return (BMI)
print(bmi_calculator())
另外,我用if语句替换了您的while weight == 0和while height == 0它们看起来更合适,我将main while循环放在函数定义bmi_calculator内,以便在需要时随时调用它。在