0

What's the difference betwen this:

print("Prime numbers between 0 and", num)
for x in range(0, num+1):
    if x > 1:
        for i in range(2, x):
            if (x % i) == 0:
                break
        else:
            print(x)

and this:

print("Prime numbers between 0 and", num)
for x in range(0, num+1):
    if x > 1:
        for i in range(2, x):
            if (x % i) == 0:
                break
            else:
            print(x)

Can i have some answer? It gives very different answer and i don't get why? Can someone enlighten me?

LeopardShark
  • 3,820
  • 2
  • 19
  • 33
  • In one case it is relative to the `for`, in the other case relative to the `if` – azro Jun 19 '22 at 12:56
  • I think your second print should be indented. – LeopardShark Jun 19 '22 at 12:57
  • indendation of the print – gil Jun 19 '22 at 12:57
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Jun 19 '22 at 12:57
  • Indentation is very important in python. It does not matter if you use tabs or spaces, but the amount of indentation determines scope. – Locke Jun 19 '22 at 12:57
  • 1
    From [`for` statement](https://docs.python.org/3/reference/compound_stmts.html#the-for-statement): *When the items are exhausted (which is immediately when the sequence is empty or an iterator raises a StopIteration exception), the suite in the else clause, if present, is executed, and the loop terminates.* – Ch3steR Jun 19 '22 at 12:59

1 Answers1

0

Python lets you attach an else clause to a for loop. It's a bit unusual, it's the only language I can think of that allows that.

The else's body will get called if the for loop completes "normally", rather than a call to break.

It might be useful to flip the question: Why would you expect the else on a for to behave the same way as on if (x % i) == 0?

Alexander
  • 59,041
  • 12
  • 98
  • 151
  • See https://stackoverflow.com/a/23748240/1126841 as well, which links to some history behind `for...else`. – chepner Jun 19 '22 at 13:01