这里,对于一个非质数,执行了内层循环的break语句,却没有执行外层循环的else语句,这是为什么呢?
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循环里面有nobreakencountered就会执行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
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循环里面有nobreakencountered就会执行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