I have been trying break out of loop when a condition is matched. I've tried one-liners below:
break if a is not None else time.sleep(1)
and this
a is not None and break
time.sleep(1)
Both are not working & throwing SyntaxError
while the straight forward works fine.
if a is not None:
break
time.sleep(1)
While I've no problem with using it this way, I just want to know why the syntax for above is wrong.
The expression expression if
expression else
expression is a ternary operator. The expressions are evaluated. break
is a statement. It isn't evaluated, it's executed. You're getting a syntax error because the syntax is not correct.
As @hugo Rivera says below, "All expressions are statements, but not all statements are expressions."
All expressions are statements, but not all statements are expressions.
The ternary operator X if B else Y
only accepts expressions X
, B
and Y
, but break
is a statement and cannot be used as an expression.
Similarly, you can't return
, import
, assign, etc... in a ternary operator. See the second link for a full list of statements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With