Reputation: 13
Why doesn't the very first iteration go to the first print statement. After all, isn't 2%2==0?
>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... break
... else:
... # loop fell through without finding a factor
... print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
Upvotes: 1
Views: 64
Reputation: 86084
2 is not in range(2, 2)
. The upper bound of range
is exclusive, so it stops before reaching it.
Upvotes: 0
Reputation: 5830
The first time through the loop, n = 2
so x
is in range(2, 2)
which is an empty list. Iterating over an empty list doesn't go into the inner loop but does executes the else
clause.
Upvotes: 1