I'm working my way through an official Python tutorial and I can't for the life of me figure out how the nested for loops work in example 4.4 :
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print n, '==', x, '*', n/x
break
else:
# loop fell through w/o finding a factor
print n, 'is a prime number'
range(2, 10)
produces: n = [2, 3, 4, 5, 6, 7, 8, 9]
,so the way I understand it the inner for loop: for x in range(2, n):
should produce (x, n-1)
and thus the following pairs of x, n
with each iteration: (2, 1), (3, 2), (4, 3), (5, 4), (6, 5), (7, 6), (8, 7), (9, 8)
. Now, obviously that would never produce n % x == 0
but that's the only way I can think about it. When I print this piece of code:
for n in range(2, 10):
for x in range(2, n):
print x, n
to check what numbers will be generated, it returns (the first 6 pairs):
2 3
2 4
3 4
2 5
3 5
4 5
How can the first pair x, n
be 2, 3
if the first n
is 2 - 1
since the last position of range()
will be excluded. I'm utterly and miserably lost.
The reason is that range(x,x)
returns an empty list. In the first iteration you call for x in range(2, n)
with n=2
. This loop is completely skipped and Python continues with the next iteration of the outer-loop.
Using the second code snippet for example:
for n in range(2, 10):
n
doesn't start from 2 - 1
, it starts with 2
, then 3
, 4
, until 9
.
In the nested loop:
for x in range(2, n):
When n
is 2
, for x in range(2, 2)
is an empty range. When n
is 3
, x
could be 2
, generating the first valid pair 2 3
. When n
is 4
, x
could be 2
and 3
, generating the second the third pair 2 4
and 3 4
. The rest is similar.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.