I cannot understand why this python function returns None if it calls itself recursively.
This was part of my solution to the Project Euler problem. I still solved the problem better, but it still annoys me, since the function seems to work fine - and it seems to know the value of the variable I wanted to return.
def next_prime(previous):
if previous % 2 == 0:
candidate = previous + 1
else:
candidate = previous + 2
print "trying", candidate
prime = True
for div in range(2,candidate//2,1):
if candidate % div == 0:
prime = False
print candidate, "is not prime - divisible by", div
next_prime(candidate)
break
if prime is True:
print candidate, "is prime"
last = 896576
print "After", last, ", the next prime is..."
next_prime(last)
This gives:
After 896576 , the next prime is...
trying 896577
896577 is not prime - divisible by 3
trying 896579
896579 is not prime - divisible by 701
trying 896581
896581 is not prime - divisible by 7
trying 896583
896583 is not prime - divisible by 3
trying 896585
896585 is not prime - divisible by 5
trying 896587
896587 is prime
But if I uncomment the return statement, it only returns a value if the first attempt is simple, otherwise it returns None.
source
share