There is an exercise in 6.00x edX whose answer’s suggestion provided by them is as follows:
def genPrimes():
primes = [] # primes generated so far
last = 1 # last number tried
while True:
last += 1
for p in primes:
if last % p == 0:
break
else:
primes.append(last)
yield last
Looking to the identation I can clearly see that this ELSE is not related to the IF. I thought it was a bug but when I executed, the code was fine and I can’t understand what is happening, what does that ELSE does?
elsepart of yourfor loopexecutes, when yourfor loopruns successfully withoutbreakingin the middle of theiteration.So, in your example, : –
if your above
if conditionin for loop becomes true in some iteration, it will break out of your for loop, and in that case your else will not execute.