Reputation: 97
Can someone please explain to me why this code works for 2 as well:
def is_prime_v1(n):
'''Return True if 'n' is prime. False otherwise.'''
if n == 1:
return False
for d in range(2,n):
if n % d == 0:
return False
return True
when the code gets to
for d in range(2,n):
if n % d == 0:
return False
return True
Would it not see this as start at 2 but go up to and do not include 2? This does not make complete sense to me. The formula works but if you try and create a list on that range like so:
x = list(range(2,2))
You get an empty list.
Please could anyone explain this to me? Does it work for two as well because it would not be able to do the below on range(2,2) and then moves down to return True?
if n % d == 0:
return False
return True
Thanks
Upvotes: 0
Views: 950
Reputation:
Your assumption is correct. The upper value of the range
function is not put through the for
loop. To overcome this, you could just add or n == 2
to the third line of your program.
Upvotes: 1
Reputation: 11247
because for loop is never executed , list(range(2,2)) == []
, so the program didn't iterate over range and directly proced to return True
statement
Upvotes: 1