Why doesn't this recursive GCD function work?

Viewed 45

I'm currently playing with recursive functions and I have a question.

I don't understand why this one work

a, b = map(int, input().split())
def gcd(a,b):
    if a%b == 0:
        return b
    else:
        return gcd(b,a%b)   
print(gcd(a,b))

but this one doesn't

a, b = map(int, input().split())
def gcd(a,b):
    if a%b == 0:
        return b
    gcd(b,a%b)

print(gcd(a,b))
1 Answers

Though the answer appears in the comments, I thought this is an opportunity to demonstrate how python tools can help you find similar errors like this in the future.

$ pylint --disable=invalid-name,redefined-outer-name,missing-function-docstring,missing-module-docstring main.py
************* Module Downloads.main
main.py:2:0: R1710: Either all return statements in a function should return an expression, or none of them should. (inconsistent-return-statements)

-------------------------------------------------------------------
Your code has been rated at 8.33/10 (previous run: 10.00/10, -1.67)

So here you see pylint points your attention to implicit return values from some path(s) in your function. Note that some of pylint's reports (the ones I disabled for instance) may generate "noise" rather than be helpful). Still, using this tool (and mypy and others) may sure help you

Related