[Tutor] Two subsequent for loops in one function
Steven D'Aprano
steve at pearwood.info
Fri Nov 22 15:52:53 CET 2013
On Fri, Nov 22, 2013 at 03:24:31PM +0100, 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")
The most tricky part here is, in my opinion, the "else" clause, because
sadly it is badly named. It really should be called "then". A for-loop
followed by an "else" means something like this:
for something in something:
run this block for each value
else:
then run this block
(Notice that the "else" lines up with the "for".)
What's the point of that? The point is that a "break" command jumps out
of the *complete* for-else block. Try these examples:
for i in range(5):
if i == 400: break
print(i)
else:
print("Finished loop!")
for i in range(5):
if i == 4: break
print(i)
else:
print("Finished loop!")
So the "else" clause only runs after the for block provided you never
break out of the loop.
Now, back to your nested loops. You have:
for x in range(2, 10):
for y in range(2, x):
... more code here ...
The "for x" loop runs with x=2, x=3, x=4, ... x=9. For each of those
values, the block inside the loop runs. Okay, so what's inside the
block? It runs another for-loop, in this case a for-y loop. This ought
to be more clear if you run a simpler (and shorter) example:
for x in range(2, 7):
print("outer loop, x =", x)
for y in range(2, x):
print("inner loop, x =", x, "y =", y)
If you run that code, it should help you understand what the nested
loops are doing.
--
Steven
More information about the Tutor
mailing list