Why Python recursive function returns None

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)

Leave a Comment