首页 > 解决方案 > 程序不升预定义 ZeroDivisionError

问题描述

我正在构建一个简单的 BMI 计算器程序,如果他们尝试零除,我希望它能够将用户带回输入字段。我定义了在那种情况下应该是什么输出,但它仍然打印出 ZeroDivisionError

def bmi_calculator():
    user_height = float(input('Enter your height in cm: '))  # user height in cm
    user_weight = float(input('Enter your weight in kg: '))  # user weight in kb
    bmi = user_weight / (user_height / 100) ** 2  # BMI formula
    while user_height <= 0 or user_weight <= 0:
        try:
            print("your weight or height can't be below or equal 0 \n enter your credentials again... ")
            user_height = float(input('Enter your height in cm: '))
            user_weight = float(input('Enter your weight in kg: '))
        except ZeroDivisionError:
            print("You can't divide by 0")
            user_height = float(input('Enter your height in cm: '))  # user height in cm
            user_weight = float(input('Enter your weight in kg: '))  # user weight in kb
    print(f'Your BMI is: {bmi}')

print(bmi_calculator())

标签: pythonpython-3.x

解决方案


那是因为您首先进行除法然后开始while循环。这应该是这样的:

def bmi_calculator():
    user_height = float(input('Enter your height in cm: '))  # user height in cm
    user_weight = float(input('Enter your weight in kg: '))  # user weight in kb

    while user_height <= 0 or user_weight <= 0:
        print("your weight or height can't be below or equal 0 \n enter your credentials again... ")
        user_height = float(input('Enter your height in cm: '))
        user_weight = float(input('Enter your weight in kg: '))

    bmi = user_weight / (user_height / 100) ** 2  # BMI formula
    print(f'Your BMI is: {bmi}')

bmi_calculator()

毕竟,我建议在循环中使用if语句以获得更多说明。while


推荐阅读