geek_code geek_code - 4 months ago 12
Python Question

Working with calculating GCD - Python function return

I wrote a code which calculates the GCD of two numbers. The gcd of (24,12) is 12. The function

compute_gcd
computes the GCD and returns it which gets printed in the main function. However, the output is
none
when I return it to the main function and it is 12 when I print it in the
compute_gcd
function itself.

Where am I going wrong while returning the GCD?

def compute_gcd(a,b):
if(b==0):
return a # Prints 12 if I replace with print a
else:
compute_gcd(b,a%b)

def main():
a=24
b=12
print compute_gcd(a,b) # Prints none

main()

Answer

You forgot to put a return in the else branch. this works:

def compute_gcd(a,b):
    if b == 0:
        return a
    else:
        return compute_gcd(b,a%b)

def main():
    a=24
    b=12

    print compute_gcd(a,b)   # Prints 12

main()