简体   繁体   中英

Python Function Return Statement is Confusing and Complex

Could any body explain what do the 'and' and 'or' statements are doing in the return statement of the function below ? the function seems to be returning the largest common denominator of a and b.

def gcd(a,b): return b and gcd(b, a % b) or a

Thank you !

The first thing we can do is put in some parenthesis:

((b and gcd(b, a % b)) or a)

Now lets take this piece by piece:

b and gcd(b, a % b)

This will give b if b is falsy. Otherwise it'll give you gcd(b, a % b) . In other words, it's equivalent to the following conditional expression:

b if not b else gcd(b, a % b)

The next part of the expression is:

(...) or a

Which will give you a if the previous expression has a falsy result, otherwise it'll give you the previous expression.

Note that this might not be what you're expecting if you come from a language like C where boolean operations return booleans :-). In python, the only boolean operation that is guaranteed to return a boolean is not . This all tends to "just work" however because python knows how to get an object's "truth value" when it needs it. eg:

if obj:
    ...

will actually check bool(obj) implicitly.


So, if I were to write out the whole thing using if suites, it would look like:

def gcd(a, b):
    if not b:  # Likely `b == 0`.  This is the recursion base-case.
         val = b
    else:
         val = gcd(b, a % d)

    if val:
        return val
    else:
        return a

The function continuously returns gcd(b, a % b) while b has a truthy value, ie not equal to zero in this case.

When b reaches 0 (after consecutively being assigned to the result of a % b ), b and gcd(b, a % b) will be False and the value of a will be returned.

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