What does your for
loop?
if x % n == 0:
return False
else:
return True
which by the way eqals return bool(x % n)
So, you return in first iteration, when n == 2
.
The whole for
loop equals return bool(x % 2)
, which simply checks if x
is diviseable by 2.
That's not what you want.
So, what do you want?
You want to check if x
is not diviseable by any numer from range(2, x)
.
You know that x
is not prime, if you find one n
from range(2, x)
, for which x % n == 0
is True
.
You know that x
is prime, when there is no n
in range(2, x)
, for which x % n == 0
is True
.
When can you say that none of n
from range is a divisor of x
?
After checking all n
s from range!
After is the key here.
After the loop, in which you try to find divisor, you can only tell that x
is prime.
I hope you now understand the code others posted without explanation.
Note: alternative syntax
Code others posted is correct. However, in Python there is second way writing the for, using for .. else
:
for x in range(2, x):
if x % n == 0:
return False
else:
return True
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…