[英]here, for a non prime number, the break statement in the inner loop is executed but the else statement of the outer loop is not executed, why?
L = []
nmax = 30
for n in range(2, nmax):
for factor in L:
if n % factor == 0:
break
else: # no break
L.append(n)
print(L)
如果 if 语句没有在内部循环中执行,那么外部循环中的 else 是否有效……尽管它们处于不同的循环中,但它们是否真的相连
else 不连接到 if 语句,而是连接到 break 语句。
for/else 语法意味着如果在 for 循环内没有遇到中断,则将执行 else 块。
下面是一个例子供大家理解:
fruits = ["Orange", "Apple", "Banana", "Strawberry"]
def searchFruit(wanted):
for fruit in fruits:
if fruit == wanted:
break
else: # Can't find the wanted fruit
return False
# Found the wanted fruit
return True
searchFruit("Tomato") # Output : False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.