GreenDog
GreenDog

Reputation: 13

Understanding python3 docs example code

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

Answers (2)

recursive
recursive

Reputation: 86084

2 is not in range(2, 2). The upper bound of range is exclusive, so it stops before reaching it.

Upvotes: 0

cmd
cmd

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

Related Questions