Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

else statement on python for loops

Hi,

looking at some example code given in the python docs to demonstrate use of for loops with an else statement.

for n in range(2, 10):
  for x in range(2, n):
    if n % x == 0:
      print(n, "equals", x, "*", n/x)
      break
  else:
    print(n, "is a prime number)"

my question is why this returns "2 is a prime number" (which it is, of course) ? I can't see how n = 2 would be processed by the inner loop when n = 2 as the range would be (2, 1), so the inner loop would never run for n = 2. If the inner loop doesn't run, then the else statement which is nested to the inner loop couldn't run either.

I'd be grateful if someone could explain what i'm not getting.

TIA.

fixed code formatting

2 Answers

Hi James,

When n = 2 the range would be (2, 2) for the inner loop but you're correct that the loop wouldn't run. The else: clause would still execute though. It will execute as long as a break statement wasn't executed.

It looks like you got your example from the tutorials page here https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

That section doesn't really completely clarify what happens if the loop doesn't run but it does say

...and a loop’s else clause runs when no break occurs.

If you follow the for loop link to the reference page it does a better job of describing when the else clause will execute.

From https://docs.python.org/3/reference/compound_stmts.html#for

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.

So what happens when n=2 is that you have an empty sequence and its immediately exhausted.

Hi Jason,

thanks for the reponse and the link was good.

Cheers.