Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Its a matter of <a href="http://docs.python.org/2/reference/expressions.html#operator-precedence" rel="nofollow">operator precedence</a>.</p> <p>In the case of your expressions, the implicit ordering is as follows</p> <pre><code>((len(str) &lt; 2) and str) or ('doh ' + str + ' /doh') </code></pre> <p>In the case of <code>str = ""</code>, <code>len(str) &lt; 2</code> evaluates <code>True</code>, but <code>str</code>, an empty string, evaluates to <code>False</code>, thus the <code>and</code> expression is <code>False</code>, so the right operand of the <code>or</code> binary op becomes the result of the expression.</p> <p>For the case of <code>str = "abc"</code>, <code>len(str) &lt; 2</code> is <code>False</code>, so the <code>and</code> expression short-circuits as <code>False</code>, and the expression to the right of the <code>or</code> is the result.</p> <p>For the case of <code>str = "ab"</code>, <code>len(str) &lt; 2</code> is True, so the <code>and</code> expression passes its right operand to the <code>or</code> binary operator, and since <code>bool("ab") == True</code>, the value of <code>str</code> becomes the result of the expression.</p> <p>As you can see, using <code>and</code>/<code>or</code> will not work similarly to other language's ternary operators if your result in the case of a <code>True</code> condition is equivalent to <code>False</code>, e.g. <code>True and 0 or 1</code> yields <code>1</code>, whereas using <code>0 if True else 1</code> yields <code>0</code>.</p> <p>I'd recommend using python's ternary if/else expression, e.g.:</p> <pre><code>str if len(str) &lt; 2 else 'doh ' + str + ' /doh' </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload