bgallday
bgallday

Reputation: 43

why is 2 printed as a prime when if statement says it should not be

I know 2 is a prime number, but when this code is ran it doesn't match the if statement condition if n % x == 0. but 2 % 2 == 0 so it should be a equal:

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

Upvotes: 0

Views: 125

Answers (1)

Barmar
Barmar

Reputation: 781708

From the Python documentation of range()

For a positive step, the contents of a range r are determined by the formula r[i] = start + step*i where i >= 0 and r[i] < stop.

A range object will be empty if r[0] does not meet the value constraint.

So when n = 2, range(2, n) is an empty range, because r[0] is 2 and that doesn't meet the constraint 2 < 2. Therefore for loop never runs, so it never breaks, and as a result, the else: block is executed and reports that it's prime.

Upvotes: 5

Related Questions