-2

I am new to python and I am just writing a simple recursive function to return the GCD of two integers. If I use a print statement in the gcd function, the function works just fine. But, if I get the function to return the value and try to print the return value outside the function, nothing is printed. This might be a small problem but I have tried numerous things and nothing worked. What am I doing wrong here?

def gcd(m,n):
    if m==n:
        return m
    else:
        if m>n:
            gcd(m-n,n)
        else:
            gcd(m,n-m)
m=int(input('Enter first number'))
n=int(input('Enter second number'))
out=gcd(m,n)
print(out)
  • Simply add `return` in front of your recursive calls to `gcd(...)` – Stephen Rauch Feb 07 '17 at 00:47
  • Possible duplicate of [Python Function Returning None](http://stackoverflow.com/questions/21471876/python-function-returning-none) – Prune Feb 07 '17 at 01:04
  • I do have a return statement in the function, unlike that question. But why doesn't the function still return a value. I got the solution, but still haven't been able to figure out the way it works. – thebuggedash Feb 07 '17 at 01:11

1 Answers1

1

When you do the recursive call, you want to also return its return value. Otherwise, whenever it calls itself, it doesn't do anything to the value it gets, and just returns None by default.

return gcd(m,n-m)
kbunarjo
  • 1,277
  • 2
  • 11
  • 27
  • It worked, but its still bugging me. I don't exactly want a return value from the recursive calls. Its just calling the function itself. Maybe its the way python works. Shouldn't the first return statement for the if condition work? – thebuggedash Feb 07 '17 at 01:01
  • @thebuggedash it does, but then the resulting value doesn't get captured, then it gets garbage collected, and your outermost call returns `None` implicitly. If no value is *explicitely* returned, the Python functions *implicitely* return `None` – juanpa.arrivillaga Feb 07 '17 at 01:09
  • @juanpa.arrivillaga Thanks. I think i got it. – thebuggedash Feb 07 '17 at 01:16
  • @thebuggedash it's the difference between `def get_max(x): max(x)` vs `def get_max(x): return max(x)` – juanpa.arrivillaga Feb 07 '17 at 01:17
  • @juanpa.arrivillaga I'm used to c++, where a return value isn't required from the recursive calls. A return value from the base case is sufficient. This is just weird for me. It might take some time getting used to. – thebuggedash Feb 07 '17 at 01:21
  • @thebuggedash uh, I'm pretty sure it works exactly the same way in C/C++ . See [this](http://stackoverflow.com/questions/28100350/why-my-recursive-function-doesnt-return-the-right-value) question which is analogous to yours. One language that implicitly returns the last expression is Scala. – juanpa.arrivillaga Feb 07 '17 at 01:32