如何使Python检查每个可能的输出,如果匹配,则打印它?

2024-04-25 01:41:04 发布

您现在位置: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,我如何使其打印所有true语句(如下所示):

Y是高的

Y是不吉利的

Y是中档


3条回答

解决方案:

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.')

解释

如果对埃利夫

elif(术语else if的缩写)条件仅在语句未触发时在上面计算。它有一些区别

你可以试试组合=7使用逻辑运算符对其他条件进行逻辑运算的条件

另外,我认为您的第11行逻辑也是错误的,您可以输入“2或3”,而不是“2和3”

类似于下面的代码。
其思想是将函数保存在一个列表中,并通过迭代列表来调用它们

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)

相关问题 更多 >