1

I don't understand the difference between these two functions, why does the one that returns the function work but the other doesn't?

The function returns the greatest common denominator between x and y assuming x > y

Non-working function:

def gcd(x, y):
    z = x % y
    if z == 0:
        return y
    else:
        gcd(y, z)

Working function:

def gcd(x, y):
    z = x % y
    if z == 0:
        return y
    else:
        return gcd(y, z)
4
  • 5
    How would you expect to get a value out of the first function if you don't return it? Commented Dec 15, 2016 at 16:54
  • 2
    Both functions work, it's just the first one doesn't return the result. Commented Dec 15, 2016 at 16:56
  • @PatrickHaugh After reading that, this makes a lot more sense now. Thank you. Commented Dec 15, 2016 at 16:59
  • In the first case, you're missing a return before the recursive function call. return makes the function "give you back" a value. Suppose you asked me to add up a list of numbers. I could simply add them up and keep the sum to myself... or I could tell you the answer. Telling you the answer (giving it back to you) is returning. Keeping it to myself (or throwing it away) is not returning, which is what you're doing in the first function Commented Dec 15, 2016 at 17:00

1 Answer 1

4

Every function in python returns something. In fact, you can put a return None statement at the end of every function in python without changing anything about how those functions work. So your first function can be written

def gcd(x, y):
    z = x % y
    if z == 0:
        return y
    else:
        gcd(y, z)
    return None

So when I call gcd(28, 14) I get None. When you return the recursive call to gcd, the code is equivalent to

def gcd(x, y):
    z = x % y
    if z == 0:
        return y
    else:
        return gcd(y, z)
    return None

so we either return 0 or whatever gcd(y, z) is, but never None, because the code never gets that far.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.