首页 > 解决方案 > 我的第一个 if 语句总是为真。未引发错误或异常

问题描述

看起来我的第一个 if 语句不起作用并且总是肯定的。我想在我的计算程序中提供选择,无论用户是否使用公制。

之后一切正常。感谢您的支持。

def bmi_calc():

    question = input('Do you use metric system?: Y/N> ')
    metric_system = None

    if question == 'Y' or 'y' or 'yes': 
        metric_system = True

        height = float(input('Enter your height in meters: '))
        weight = float(input('Enter your weight in kilograms: '))

    elif question == 'N' or 'n' or 'no':
        metric_system = False

        height = float(input('Enter your height in feets: '))
        weight = float(input('Enter your weight in pounds: '))

    else:
        'incorrect answer'
        bmi_calc()

    bmi = None

    if metric_system == True:
        bmi = weight / (height ** 2)
    elif metric_system == False:
        bmi = weight / (height ** 2) * 703

    print(f'Your body mass index is {bmi:.2f}')

标签: pythonpython-3.x

解决方案


它应该是:

if question == 'Y' or question == 'y' or question == 'yes': 
    metric_system = True

    height = float(input('Enter your height in meters: '))
    weight = float(input('Enter your weight in kilograms: '))

elif question == 'N' or question == 'n' or question == 'no':
    metric_system = False

    height = float(input('Enter your height in feets: '))
    weight = float(input('Enter your weight in pounds: '))

else:
    'incorrect answer'
    bmi_calc()

原因是因为:if 'y':将永远是True


推荐阅读