python - 我的第一个 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}')
解决方案
它应该是:
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
推荐阅读
- c# - Avalonia 中的 GetTemplateChild / TemplatePart?
- google-sheets - 仅当时间为 0:00 时才从单元格中删除时间
- sql - 嵌套的 while 语句仅在内部运行 SQL
- java - 将 void 函数的结果传递给 double 函数
- c++ - 没有参数的递归参数包函数 C++
- python - 将所有类变量添加到列表
- javascript - 正则表达式字符串组不同的状态
- yaml - 用 Yaml2 中的值替换标记 Yaml1
- jquery - 如何在 .NET 5 中使用 Jquery Ajax Post 发送大型 json 数据
- javascript - 在过滤器函数中使用变量作为键名