Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't if else shorthand work with break - Python

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.

like image 516
Vishwa Avatar asked Jan 06 '23 17:01

Vishwa


2 Answers

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."

like image 124
vy32 Avatar answered Jan 20 '23 01:01

vy32


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.

like image 29
Hugo O. Rivera Avatar answered Jan 20 '23 00:01

Hugo O. Rivera