首页 > 解决方案 > BMI与异常处理python

问题描述

我需要帮助我尝试应用此代码,不久前我在索引中运行了一个 bmi 计算器,现在我正在尝试使用异常处理更新该代码。到目前为止,这些部分并没有给我错误,它们只是奇怪地一起运行。例如,当它提示“输入用户名或‘0’退出”时,它实际上并没有结束进程,而是继续到异常进程。有人可以帮我更有效地写这个。这是我更新的代码,我现在特别遇到的问题是当用户输入“0”时程序没有终止:

def bmi_calculator():
end = False

print("Welcome to the BMI Calculator!")

while end == False:

    user = input("Enter student's name or '0' to quit: ")
    if user == "0":
        print("end of report!")
        end = True
    else:
        print("Lets gather your information,", user)
        break

flag='yes'
while flag != 'no':
    #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(" Your bmi is:", bmi_calculator())

标签: pythonsyntaxexception-handling

解决方案


推荐阅读