Python issues with return statement
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzling Curiosities
--
Chapters
00:00 Question
00:53 Accepted answer (Score 10)
01:27 Thank you
--
Full question
https://stackoverflow.com/questions/1717...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #return
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzling Curiosities
--
Chapters
00:00 Question
00:53 Accepted answer (Score 10)
01:27 Thank you
--
Full question
https://stackoverflow.com/questions/1717...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #return
#avk47
ACCEPTED ANSWER
Score 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