简体   繁体   中英

Function would not return value, instead it returns “None”

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM