[Tutor] Two subsequent for loops in one function

Rafael Knuth rafael.knuth at gmail.com
Fri Nov 22 15:24:31 CET 2013


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?

Thanks

Rafael


More information about the Tutor mailing list