开发者

Assigning return value of a function to a variable

开发者 https://www.devze.com 2023-03-13 20:11 出处:网络
I\'m having 开发者_StackOverflow中文版a hard time understanding why I can\'t assign a return value from this simple function to the variable gcd:

I'm having 开发者_StackOverflow中文版a hard time understanding why I can't assign a return value from this simple function to the variable gcd:

def euclidAlgorithm(m, n):
    if n == 0:
        print "n cannot be zero."
        return -1
    r = m % n # Remainder
    if r == 0:
        return n
    else:
        euclidAlgorithm(n, r)

if __name__ == "__main__":
    #Input values
    m = 54
    n = 36

    print "Input : m = ", m, " n = ", n
    gcd = euclidAlgorithm(m, n)
    if gcd == -1:
        print "Function terminated with an error"
    else:
        print "Output: gcd = ", gcd

Instead of getting gcd as 18 I get this when I run it:

Input : m =  119  n =  4
Output: gcd =  None


You're missing a return statement at the end of your euclidAlgorithm(m, n). Like this:

def euclidAlgorithm(m, n):
    if n == 0:
        print "n cannot be zero."
        return -1
    r = m % n #Remainder
    if r == 0:
        return n
    else:
        return euclidAlgorithm(n, r)


You forgot to return the result of your recursion.

 ...
else:
    return euclidAlgorithm(n, r)


You forgot return:

return euclidAlgorithm(n, r)


In the recursive case, your function isn't returning anything.


Without return keyword, the function makes a recursive call but there is no return value till the base conditions are reached.

Refer : How does using a return clause before a recursive function call differ from not using one?

Hence, return is important.

0

精彩评论

暂无评论...
验证码 换一张
取 消