Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The advantage of the inline <code>if</code> expression is that it's an expression, which means you can use it inside other expressions—list comprehensions, lambda functions, etc. </p> <p>The disadvantage of the inline <code>if</code> expression is <em>also</em> that it's an expression, which means you can't use any statements inside of it.</p> <hr> <p>A perfect example of the disadvantage is exactly what's causing your error: <code>a = a/w</code> is a statement, so you can't use it inside an expression. You have to write this:</p> <pre><code>if b == 2: a = a*2 else: a = a/w </code></pre> <p>Except that in this particular case, you just want to assign something to <code>a</code> in either case, so you can just write this:</p> <pre><code>a = a*2 if b==2 else a/w </code></pre> <p>As for the advantage, consider this:</p> <pre><code>odd_numbers = [number if number%2 else number+1 for number in numbers] </code></pre> <p>Without the <code>if</code> expression, you'd have to wrap the conditional in a named function—which is a good thing for non-trivial cases, but overly verbose here:</p> <pre><code>def oddify(number): if number%2: return number else: return number+1 odd_numbers = [oddify(number) for number in numbers] </code></pre> <p>Also, note that the following example is <em>not</em> using an <code>if</code> (ternary conditional) expression, but an <code>if</code> (conditional filter) clause:</p> <pre><code>odd_numbers = [number for number in numbers if number % 2] </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