4

Hello I'm very new to python and was wondering if you could help me with something. I've been playing around with this code and can't seem to get it to work.

    import math

def main():
    if isPrime(2,7):
        print("Yes")
    else:
        print("No")

def isPrime(i,n):
    if ((n % i == 0) and (i <= math.sqrt(n))):
        return False
    if (i >= math.sqrt(n)):
        print ("is Prime: ",n)
        return True
    else:
        isPrime(i+1,n)
main()

Now the output for the isPrime method is as follows:

is Prime:  7
No

I'm sure the function should return true then it should print "Yes". Am I missing something?

1 Answer 1

10

You are discarding the return value for the recursive call:

def isPrime(i,n):
    if ((n % i == 0) and (i <= math.sqrt(n))):
        return False
    if (i >= math.sqrt(n)):
        print ("is Prime: ",n)
        return True
    else:
        # No return here
        isPrime(i+1,n)

You want to propagate the value of the recursive call too, include a return statement:

else:
    return isPrime(i+1,n)

Now your code prints:

>>> isPrime(2,7)
is Prime:  7
True
Sign up to request clarification or add additional context in comments.

2 Comments

why dont you just add the return to the answer? then I can delete my answer :P
hehe bah testing is for wimps :P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.