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
块,并且该块没有被执行。有人可以指导我为什么它不执行吗?
是,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
没有其他的“如果”。我认为您需要这样的东西:
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)
缩进似乎是错误的,请尝试此。
for num in numbers:
if num % 2 == 0:
print(num)
break
else:
print(num)
我认为最好通过各种测试来证明这一点。因此,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