Python function returns None after recursion

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"
        #return candidate

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.

+3
source share
3 answers

You forgot to return the value when you cannot find the prime:

for div in range(2,candidate//2,1):
    if candidate % div == 0:
        prime = False
        print candidate, "is not prime - divisible by", div
        return next_prime(candidate)

. . , , , .

+6

, . . , - , .

def is_prime(n):
    """Return True if n is prime."""
    for i in xrange(2, n//2):
        if n%i == 0:
            return False
    return True

def next_prime(n):
    """Returns the next prime number after n."""
    if n % 2 == 0:
        candidate = n + 1
    else:
        candidate = n + 2
    while not is_prime(candidate):
        candidate += 2
    return candidate

if __name__ == '__main__':
    n = 896576
    print next_prime(n)
+1

Note that you make recursive calls to the next_prime function, but do not return a value from it from the calling function.

Replace the lines:

print candidate, "is not prime - divisible by", div
next_prime(candidate)

from

print candidate, "is not prime - divisible by", div
return next_prime(candidate)
0
source

Source: https://habr.com/ru/post/1728848/


All Articles