应该检查每个数字并得到错误的输出

我有一个任务:在输入 [x;y] 上有一个范围,然后我应该检查该范围内的每个数字并检查数字中的每个数字。如果它很奇怪,我应该打印它,例如:3, 20 我应该打印 4,6,8,20


def check(num):

if int(num) % 2 == 0:

    return True



x, y = int(input()), int(input())


numbers = []

if x <= y:

while x != y:

    for i in str(x):

        if check(i):

            numbers.append(x)

    x += 1


else:

while y != x:

    for i in str(y):

        i = int(i)

        if check(i):

            numbers.append(y)

    y += 1

if y == x:

    for i in str(x):

        if check(i):

            numbers.append(x)

print(numbers)

它打印 [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 20, 21, 22, 22, 23, 24, 24, 25, 26, 26, 27, 28, 28, 29 ] 而不是 2,4,6,8,20,22,24,26,28


Smart猫小萌
浏览 98回答 1
1回答

开满天机

您正在根据每个数字的单个数字进行检查和批准。在附加整个数字之前,您应该检查所有这些。这就是您获得22两次的原因:第一次获得2一次,第二次获得一次。你得到10,因为即使1是奇数,0也是偶数,所以你将它附加到你的列表中。将整个数字的检查移到函数中,并且仅当所有数字都是偶数时才check返回。这会缩短您的代码。另请注意,如果用户以错误的顺序输入它们,您可以轻松交换。True xy一旦发现一个数字是奇数,该函数check就会立即返回,您可以看到它只有在循环结束并且所有数字都是偶数时才能返回。FalseiTrue&nbsp; &nbsp; def check(num):&nbsp; &nbsp; &nbsp; &nbsp; for i in str(num):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if int(i) % 2 != 0:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return False&nbsp; &nbsp; &nbsp; &nbsp; return True&nbsp; &nbsp; x, y = int(input()), int(input())&nbsp; &nbsp; if x > y:&nbsp; &nbsp; &nbsp; &nbsp; x,y = y,x&nbsp; &nbsp; numbers = []&nbsp; &nbsp; while x <= y:&nbsp; &nbsp; &nbsp; &nbsp; if check(x):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; numbers.append(x)&nbsp; &nbsp; &nbsp; &nbsp; x += 1&nbsp; &nbsp; print (numbers)结果,3并20输入(但20也3可以):[4, 6, 8, 20]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python