3

I am relatively new to python, and have been working on a problem to find the prime numbers between two inputs. I have a solution that works (helped somewhat by online searching too), but am unsure on why the else statement shown below should not be at the same tab setting as the if statement. If it is, though, it doesn't work correctly. Can anyone clarify this for me?

My code is here:

n1 = int(input("Enter the lower number: "))
n2 = int(input("Enter the higher number: "))

for num in range(n1, n2 + 1):
    if num > 1:
        for i in range(2, num):
            if num % i == 0:
                break
        else:
            print(num)
Jeff Learman
  • 2,914
  • 1
  • 22
  • 31
Seq76
  • 57
  • 4
  • 1
    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) – Guy Dec 03 '19 at 12:04
  • Have a look at this example in the documentation: https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops – natka_m Dec 03 '19 at 12:06
  • think of it this way. you could have defined a variable `found = False` above you inner loop. then when you have a % modulo 0 remainder you’d set `found = True` before `break`. then, without that loop-else, you'd know it was a prime if found was still False at the end. The loop-else allows you to skip tracking variable in these types of cases. – JL Peyret Dec 04 '19 at 01:50

1 Answers1

7

You're seeing Python's (rather unique) for:else: pattern, to execute something when a break is not encountered within the for suite:

When the items are exhausted, the suite in the else clause, if present, is executed, and the loop terminates.
A break statement executed in the first suite terminates the loop without executing the else clause’s suite. [...]

AKX
  • 152,115
  • 15
  • 115
  • 172