To put it in slightly simpler terms, you're misusing the 'one-line if
statement' (ternary operator). It always evaluates to an expression (i.e., a value). That is,
<expr1> if <condition> else <expr2>
evaluates to <expr1>
if <condition>
is True
, and to <expr2>
if <condition>
is False
. This resulting value can then be used like any Python value, for example:
y = 0
x = (5 if (y > 0) else 6)
print(x) # 6
Of course, the parentheses are completely unnecessary (even discouraged), but hopefully are useful for understanding the meaning of that line.
Therefore,
print(a) if a > 0 else break
tries to evaluate print(a)
(which, by the definition of print()
in Python 3, always returns None
– perfectly valid, but probably not what you usually want) and then break
, which does not evaluate to anything because it is a statement (action), not an expression (value), hence the invalid syntax
error.
Hence, if you want to execute one of two statements depending on a condition, you really need the multi-line solution proposed by
Willem Van Onsem. There may be hacky ways to do it in one line, but multiple lines is the usual solution for something like this in Python.