Python: 有没有办法打印未知范围内的偶数而不用 if 语句?

Python: Is there a way to print even numbers within an unknown range and without if statement?

我在 Python class 有作业要做,被问到这个问题:

Make a program that gets 2 numbers from the user, and prints all even numbers in the range of those 2 numbers, you can only use as many for statements as you want, but can't use another loops or if statement.

我知道我需要使用这个代码:

for num in range (x,y+1,2):
    print (num)

但没有任何 if 语句,我无法检查插入的值 x 是偶数还是奇数,以及用户是否将数字 5 插入为 x,所有的印都是奇数。

我也尝试过将每个数字输入元组或数组,但我仍然无法检查第一个数字是否为偶数以开始打印。

def printEvenFor(x,y):
    evenNumbers =[]
    for i in range (x,y+1):
        evenNumbers.append(i)
    print (evenNumbers[::2])

def printEvenFor(x,y):
    for i in range (x,y+1,2):
        print(i,",")

我希望 printEvenFor(5,12) 的输出是 6,8,10,12 但它是 5,7,9,11

你可以通过先除法再乘法使 x 为偶数:

x = (x // 2) * 2

x 将四舍五入为前一个偶数或保持不变(如果为偶数)。

如果你想将它四舍五入到下面的偶数,你需要做的是:

x = ((x + 1) // 2) * 2

这可以通过使用移位运算符进一步改进:

x = (x >> 1) << 1         #Alternative 1
x = ((x + 1) >> 1) << 1   #Alternative 2

示例:

#Alternative 1
x = 9
x = (x >> 1) << 1
#x is now 8

#Alternative 2
x = 9
x = ((x + 1) >> 1) << 1
#x is now 10

第二个可能更适合你

试试这个:

x = x+x%2
for num in range (x,y+1,2):
    print (num)

你可以这样做:

>>> for n in range((x + 1) // 2 * 2, y+1, 2):
        print(n)

range 的第一个参数强制它成为下一个偶数(如果它是奇数)。最后一个参数成对上升。

def printEvenfor(x,y):
    return list(range(((x+1) // 2) * 2,y+1, 2))

printEvenfor(9,16)

以下函数将执行您想要的操作。我使用 round 强制边界为偶数,以便以偶数开始范围。

def print_even_between(x, y):
    x = round(x / 2) * 2
    y = round(y / 2) * 2

    for i in range(x, y, 2):
        print(i)  
    print(y)

您可以使用提醒来获取正确的范围:

def print_event_for(min_, max_):
    reminder = min_ % 2
    for i in range(min_+reminder, max_+reminder, 2):
        print(i)

print_event_for(5, 12)

输出:

6
8
10
12

一种方法是使用 while,它采用

中的开始和结束范围
for each in range(int(input()),int(input())):
    while each%2 == 0:
       print (each)
       break; 

Hacky 但有趣:将字符串与零相乘。

>>> low, high = int(input()), int(input())
5
13
>>> for n in range(low, high + 1):
...     print('{}\n'.format(n)*(not n%2), end='')
... 
6
8
10
12

不打印奇数,因为字符串乘以 False(充当零)。