Why Python recursive function returns None

The following code returns None on some values (eg 306, 136), on some values (42, 84), it returns the answer correctly. The print a and return a should yield the same result, but it does not:

def gcdIter (a,b):     c = min (a,b)     d = max (a,b)     a = c     b = d      if (b%a) == 0:         print a         return a     gcdIter (a,b%a)       print gcdIter (a,b) 
Add Comment
1 Answer(s)

You are ignoring the return value for the recursive call:

gcdIter (a,b%a)  

Recursive calls are no different from calls to other functions; you’d still need to do something with the result of that call if that is what you tried to produce. You need to pass on that return value with return

return gcdIter (a,b%a)     

Note that you can assign to multiple targets when assigning:

def gcdIter(a, b):     a, b = min(a, b), max(a, b)     if b % a == 0:         return a     return gcdIter(a, b % a)   

You really don’t need to care about the bigger and smaller values here. A more compact version would be:

def gcd_iter(a, b):     return gcd_iter(b, a % b) if b else abs(a) 
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.