Reputation: 43
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
Reputation: 781708
From the Python documentation of range()
For a positive step, the contents of a range
r
are determined by the formular[i] = start + step*i
wherei >= 0
andr[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