0
# Write a program to display all prime numbers within a range

start = 25
end = 50

for num in range(start, end + 1):
    if num > 1: # all prime #s are greater than 1
        for i in range(2,num):
            if (num % i) == 0:
                break
        else:
            print(num)

Why is it that the else is written directly under the second for?

Is it that it's not necessarily under the for but instead, outside of the for-loop? Therefore, running every item in the range and checking the ones that are not prime in the for-loop as well as the ones that are during the else?

If that's the case, then why is it that there is break? Doesn't the break immediately stop the entire process and keep the loop ever reaching the else statement? Or does it only stop the current for-loop-- allowing the else statement to run?

I suppose I just need help understanding what's going on.

Antonio
  • 417
  • 2
  • 8
  • In a `for/else`, the `else` part only executes if no `break` is hit in the `for`. In this example, a `break` is hit when the number is not prime, so the `print(num)` doesn't get executed in that case. – 001 Dec 22 '22 at 20:32
  • In my case, why is it reaching the `else` if it is definitely hitting the `break` for some non-prime numbers? – Antonio Dec 22 '22 at 20:34
  • 1
    The `else` goes with the inner `for` as does the `break`. Each iteration of the outer `for` loop "resets" the `for/else`. – 001 Dec 22 '22 at 20:41
  • oh! That makes so much sense. Thank you – Antonio Dec 22 '22 at 20:49
  • Does this answer your question? [Why does python use 'else' after for and while loops?](https://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops) – Pranav Hosangadi Dec 22 '22 at 21:03

1 Answers1

0

I’m no python expert, but looked it up. You have 2 for loops. This first one iterated the number from start to end. The second one tests if the number (of the first for loop) is a prime. If the number is % i == 0 (The modulo (or "modulus" or "mod") is the remainder after dividing one number by another.) then it’s not a prime number so no print. It breaks the second for loop. And iterates to the next number of the first for loop. If the number is not % i == 0 then it’s a prime number and it will be printed.