[Tutor] Two subsequent for loops in one function

Don Jennings dfjennings at gmail.com
Fri Nov 22 16:07:44 CET 2013


On Nov 22, 2013, at 9:24 AM, Rafael Knuth wrote:

> Hej there,
> 
> newbie question: I struggle to understand what exactly those two
> subsequent for loops in the program below do (Python 3.3.0):
> 
> for x in range(2, 10):
>    for y in range(2, x):
>        if x % y == 0:
>            print(x, "equals", y, "*", x//y)
>            break
>    else:
>        print(x, "is a prime number")

Let's step through the code. The outer for loop will iterate over the values of range(2, 10):

>>> range(2, 10)
[2, 3, 4, 5, 6, 7, 8, 9]

So, each time the loop executes, x will be one of the values in that list. The inner loop then checks to see if any values up to but not including that value are evenly divisible by it. Let's choose 5 to see what will happen during that loop. The inner loop will then iterate over the values of range(2, 5):

>>> range(2, 5)
[2, 3, 4]

So, here is what happens during the x % y:

>>> 5 % 2
1
>>> 5 % 3
2
>>> 5 % 4
1

It is never equal to 0; the print(x, "is a prime number") will execute. Perhaps it's the "else" clause which is confusing? From the tutorial [1], I quote:

When used with a loop, the else clause has more in common with the else clause of a try statement than it does that of if statements: a try statement’s else clause runs when no exception occurs, and **a loop’s else clause runs when no break occurs**. (emphasis mine)

Take care,
Don

[1] http://docs.python.org/3/tutorial/controlflow.html


More information about the Tutor mailing list