[英]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.