我如何做到这一点,以便Python检查每个可能的输出,如果与之匹配,则将其打印出来?

问题描述

我当前的代码是这样:

y = int(input('Please enter a number from 1 - 100: '))

if y == 1:
    print('Y is 1.')
elif y >= 5:
    print('Y is high.')
elif y <= 5:
    print('Y is low.')
elif y != 7:
    print('Y is unlucky.')
elif y == 2 and y == 3:
    print('Y is 2 or 3.')
elif y >= 4 and y <= 7:
    print('Y is mid range.')

如果用户输入的Y为6,我该如何做才能打印所有真实的语句(如下所示):

Y高

你真倒霉

Y是中等范围

解决方法

解决方案:

y = int(input('Please enter a number from 1 - 100: '))

if y == 1:
    print('Y is 1.')
if y >= 5:
    print('Y is high.')
elif y <= 5:
    print('Y is low.')
if y != 7:
    print('Y is unlucky.')
if y == 2 and y == 3:
    print('Y is 2 or 3.')
if y >= 4 and y <= 7:
    print('Y is mid range.')

解释

if vs elif吗?

elif(“ if if”的缩写)条件仅在未触发语句的情况下才求值。它有一些区别。

,

类似下面的代码。
想法是将函数保留在列表中,并通过迭代列表来调用它们

y = int(input('Please enter a number from 1 - 100: '))


def a(num):
    if num == 1:
        print('Y is 1.')


def b(num):
    if num >= 5:
        print('Y is high.')


functions = [a,b]  # TODO: implement more functions

for func in functions:
    func(y)
,

您可以尝试结合!= 7个条件,将逻辑运算符用于其他所有条件。

P.S。我认为您的第11行逻辑也很错误,您可以输入“ 2或3”而不是“ 2和3”