In fact, the indentation serves to define which structure else
belongs. In the first case, else
belongs to the for
loop (yes, that exists in Python), while in the second else
would belong to if
.
for i in range(2, n):
for j in range(2, i):
if i % j == 0 and i != j:
break
else:
print(i)
In this case, the value of i
will vary from 2 to n-1
and the value of j
will vary from 2 to i-1
. If a value of j
is found that is a divisor of i
, the j
loop is broken. The else
block will be executed whenever the loop terminates without interruption, that is, if the value of j
reaches i-1
, which is its upper limit, without one of its values being i
. If break
occurs, the else
block will not run. It is worth mentioning that the i != j
condition here is unnecessary since j
will not reach i
since its upper limit is i-1
.
As for the second case:
for i in range(2, n//2):
for j in range(2, i):
if i % j == 0 and i != j:
break
else:
print(i)
The else
block will be executed at each loop in j
where the j
value is not a i
splitter, which is likely to generate a result far beyond what is expected.