1

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?

cph_sto
  • 7,189
  • 12
  • 42
  • 78
  • It's true that the `else` doesn't have an `if`, but that doesn't make it standalone. It's paired with the `for`, see the duplicate for a fuller explanation. – Daniel Roseman Apr 17 '19 at 08:06
  • In this particular snippet, you could argue it could be seen as paired with the `if` inside the loop: if that `if` statement never evaluates to `True`, the `else` part is executed. It's not actually true, but it's another way to look at it. – 9769953 Apr 17 '19 at 08:09
  • Also (another) duplicate: https://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops – 9769953 Apr 17 '19 at 08:10
  • @9769953 Yeah, that part is fine. I would have implemented it exactly the way you are suggesting, but this "stand alone" `else` confounded me. – cph_sto Apr 17 '19 at 08:23
  • @DanielRoseman Thanks a ton for refering me to this link. Now, I understand this concept. – cph_sto Apr 17 '19 at 08:26

0 Answers0