1

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I thought that range would have a single element: [2].
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.