I recently noticed this snippet of code to find prime numbers
between a range of numbers. Let me put the code here as well -
start = 11
end = 25
for val in range(start, end + 1):
# If num is divisible by any number
# between 2 and val, it is not prime
for n in range(2, int(val/2)+1):
if (val % n) == 0:
break
else:
print(val)
11
13
17
19
23
If the inner for loop
is exhausted without getting remainder
0 for any of the divisors, then the said number is a prime number
. In this case this else
, which doesn't even have its corresponding if
, gets executed thereby printing the prime number. But, in case we found a divisor which produces 0 as remainder, then we break
from the inner for
loop, but this time the else
is not executed.
My question: What is this construct where we can have an else
statement without its engendering if
statement? Can anyone explain as to how this construct even works?