[Tutor] Two subsequent for loops in one function
Peter Otten
__peter__ at web.de
Fri Nov 22 15:35:51 CET 2013
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 result is:
>
>>>>
> 2 is a prime number
> 3 is a prime number
> 4 equals 2 * 2
> 5 is a prime number
> 6 equals 2 * 3
> 7 is a prime number
> 8 equals 2 * 4
> 9 equals 3 * 3
>
> I have a very basic understanding of for loops, so for example:
>
> for everything in range(10):
> print(everything)
>
> ... the for loop grabs everything in that given range and prints it.
> But I feel confused by the double use of for loops as show above.
>
> Can anyone explain?
Try to understand the inner for loop first. Once you understand what it does
treat it as a black box like so:
def unknown(x):
for y in range(2, x):
if x % y == 0:
print(x, "equals", y, "*", x//y)
break
else:
print(x, "is a prime number")
for x in range(2, 10):
unknown(x)
More information about the Tutor
mailing list