Python:有没有一种方法可以打印未知范围内的偶数而不使用if语句?

2024-10-01 13:35:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python课堂上有一个作业要做,有人问我:

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插入,则所有打印都将是奇数。在

我还试图将每个数字输入到一个元组或数组中,但我仍然无法检查第一个数字是否要开始打印。在

^{pr2}$

或者

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

我希望printEvenFor(5,12)的输出是6,8,10,12,但它是{}


Tags: theinyouforifuseasrange
3条回答

一种方法是使用while,它将起始和结束范围

for each in range(int(input()),int(input())):
    while each%2 == 0:
       print (each)
       break; 

您可以通过使用底数除法和乘法使x为偶数:

x = (x // 2) * 2

x将被四舍五入到前一个偶数整数,如果是偶数,则保持不变。在

如果要将其四舍五入为以下偶数整数,则需要执行以下操作:

^{pr2}$

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

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

第二种可能更适合你

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

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)

输出:

^{pr2}$

相关问题 更多 >