Python Function Return Statement is Confusing and Complex
<p>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.  </p>

<p> <code>def gcd(a,b): return b and gcd(b, a % b) or a</code></p>

<p>Thank you !</p>

<p>The first thing we can do is put in some parenthesis:</p>

<pre><code>((b and gcd(b, a % b)) or a)
</code></pre>

<p>Now lets take this piece by piece:</p>

<pre><code>b and gcd(b, a % b)
</code></pre>

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

<pre><code>b if not b else gcd(b, a % b)
</code></pre>

<p>The next part of the expression is:</p>

<pre><code>(...) or a
</code></pre>

<p>Which will give you <code>a</code> if the previous expression has a falsy result, otherwise it'll give you the previous expression.</p>

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

<pre><code>if obj:
    ...
</code></pre>

<p>will actually check <code>bool(obj)</code> implicitly.</p>

<hr>

<p>So, if I were to write out the whole thing using <code>if</code> suites, it would look like:</p>

<pre><code>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
</code></pre>

python python-2.7 function python-3.x