[Tutor] Nested for loops

Rafael Knuth rafael.knuth at gmail.com
Wed Nov 27 17:08:11 CET 2013


Hej there,

I am trying to figure out how exactly variables in nested loops are
generated, and don't get it 100% right yet. Here's my code:

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')

And here's what I assume happens inside these for loops:

#1 Round:
n = 2
x = no result
>>>
2 is a prime number

#2 Round:
n = 3
x = 2
>>>
3 is a prime number

#3 Round:
n = 4
x = 3
>>>
My assumption about the way these two for loops work is wrong, because
the output cannot be "4 is a prime number" for obvious reasons.

Can anyone help me understand?
I am using Python 3.3.0. Thank you!

All the best,

Raf


More information about the Tutor mailing list