Reputation: 27
Please help me look at this piece of code which was supposed to calculate the greatest common division between two numbers (a, b)
. The problem I'm having is that the program would not return c
as expected, instead it return None
. But when I use a print
statement, it prints out the value of c
.
This is my code:
def gcd(a, b):
if a == 0:
return b
elif b == 0:
return a
elif a > b:
big, small = a, b
else:
big, small = b, a
c = big % small
if c == 0:
print(small)
return small
gcd(small, c)
print(gcd(1071, 462))
Thanks guys.
Upvotes: 0
Views: 46
Reputation: 152647
Python implicitly returns None
when no explicit return
is encountered and the function body ends.
In your case if it passes through all other cases it just hits:
gcd(small, c)
return None # you haven't put that in explicitly but that's how Python processes it
So you probably just need to change the last line to:
return gcd(small, c)
Upvotes: 1