In the second example, the else
is on the same indentation level as the if
, so they both belong together. So for the first item in the loop, you will either return False
or True
depending on that value; i.e. the loop won’t continue.
Now in your original code, the else
is on the same level as the for
. So it’s a for..else
which is actually a special construct:
When the items are exhausted, the suite in the else
clause, if present, is executed, and the loop terminates.
So basically, the else block is executed, if the loop naturally finishes (without calling break
). So in your case, it’s the same as leaving the else
out:
for i in range(2,x):
if x % i == 0:
return False
return True