I'm a little curious about the difference between if and inline if, in Python. Which one is better?
Is there any reason to use inline if, other than the fact that it's shorter?
Also, is there anything wrong with this statement? I'm getting a syntax error: SyntaxError: can't assign to conditional expression
a = a*2 if b == 2 else a = a/w
The advantage of the inline
ifexpression is that it's an expression, which means you can use it inside other expressions—list comprehensions, lambda functions, etc.The disadvantage of the inline
ifexpression is also that it's an expression, which means you can't use any statements inside of it.A perfect example of the disadvantage is exactly what's causing your error:
a = a/wis a statement, so you can't use it inside an expression. You have to write this:Except that in this particular case, you just want to assign something to
ain either case, so you can just write this:As for the advantage, consider this:
Without the
ifexpression, you'd have to wrap the conditional in a named function—which is a good thing for non-trivial cases, but overly verbose here:Also, note that the following example is not using an
if(ternary conditional) expression, but anif(conditional filter) clause: