是否在for循环之外,如果是,为什么不执行?

问题描述 投票:-1回答:3
numbers = [10, 20, 33, 55, 39, 55, 75, 37, 21, 23, 41, 13]

for num in numbers:
    if num % 2 == 0:
       print(num)
       break
else:
   print(num)

在上面的代码中,我确实具有与else循环对应的for块,并且该块没有被执行。有人可以指导我为什么它不执行吗?

python loops for-loop indentation
3个回答
3
投票

是,else块对应于for循环(这在for循环之外),但是仅当从不执行break时才执行。由于您在numbers中有偶数,因此会执行中断,这就是为什么else未执行的原因

for num in numbers:
  if num % 2 == 0:
     print(num)
     break
else:
  print(num)

尝试使用此列表number=[11,22,33],将执行else块,有关更多信息4.4. break and continue Statements, and else Clauses on Loops


0
投票

没有其他的“如果”。我认为您需要这样的东西:

numbers = [10, 20, 33, 55, 39, 55, 75, 37, 21, 23, 41, 13]

for num in numbers:
    if num % 2 == 0:
        print(num)
        break
print(num)

0
投票

缩进似乎是错误的,请尝试此。

for num in numbers:
    if num % 2 == 0:
        print(num)
        break
    else:
        print(num)

0
投票

我认为最好通过各种测试来证明这一点。因此,for循环可以具有else块。仅在循环正常完成时才执行else块。即,循环中没有break。如果我们创建一个接受列表和分隔符的函数。我们可以看到,如果if条件匹配并且我们先打印然后中断,则else块将永远不会运行。仅当我们在没有break的情况下一直运行循环时,才执行else

def is_divisable_by(nums, divider):
    for num in nums:
        if num % divider == 0:
            print(num, "is divsiable by ", divider)
            break
    else:
        print("none of the numbers", nums, "were divisable by", divider)

numbers = [1, 6, 3]
numbers2 = [7, 8, 10]
is_divisable_by(numbers, 2)
is_divisable_by(numbers, 7)
is_divisable_by(numbers2, 4)
is_divisable_by(numbers2, 6)

输出

6 is divsiable by  2
none of the numbers [1, 6, 3] were divisable by 7
8 is divsiable by  4
none of the numbers [7, 8, 10] were divisable by 6
© www.soinside.com 2019 - 2024. All rights reserved.