Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python issues with return statement

Tags:

python

return

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?

like image 690
Warosaurus Avatar asked Aug 31 '25 17:08

Warosaurus


1 Answers

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
like image 78
Martijn Pieters Avatar answered Sep 02 '25 05:09

Martijn Pieters