Why not, unless otherwise shorthand work with a break - Python

I try to exit the loop when the condition is agreed. I tried single line below:

break if a is not None else time.sleep(1)

and this one

a is not None and break
time.sleep(1)

Both do not work and throw SyntaxError, while straight forward works great.

if a is not None:
    break
time.sleep(1)

While I have no problem using this method, I just want to know why the syntax above is incorrect.

+4
source share
2 answers

expression expression ifexpression elseexpression is a ternary operator. Expressions are calculated. break- this statement. He is not being evaluated; he is being fulfilled. You get a syntax error because the syntax is incorrect.

@hugo Rivera : " - , ".

+5

, .

X if B else Y X, B Y, break .

, return, import, .. . . .

+2

Source: https://habr.com/ru/post/1626811/


All Articles