Why does "if-else-break" break in python?

I am trying to use an if-else statement that should break the loop if the condition is ifnot met but gets an error invalid syntax.

Code example:

a = 5
while True:
    print(a) if a > 0 else break
    a-=1

Of course, if I write in the traditional way (without using one liner), it works.

Please let me know what is wrong if you use the command breakafter the keyword else.

+4
source share
3 answers

If I run this, I get the following error:

...     print(a) if a > 0 else break
  File "<stdin>", line 2
    print(a) if a > 0 else break
                               ^
SyntaxError: invalid syntax

It's because

print(a) if a > 5 else break

. - no if. :

<expr1> if <expr2> else <expr3>

" ":

def f():
    if <expr2>:
        return <expr1>
     else:
         return <expr3>

, , else . break , . Python . return a break.

, print . print. print .

:

a = 5
while True:
    if a > 5:
        print(a)
    else:
        break
    a -= 1

PEP-308.

+13

If , break, return, . ( , ). , , , , , .

+5

, one-line if ( ). (.. ).

<expr1> if <condition> else <expr2>

<expr1>, <condition> True, <<25 > , <condition> - False. Python, :

y = 0
x = (5 if (y > 0) else 6)
print(x) # 6

, ( ), , , .

,

print(a) if a > 0 else break

print(a) ( print() Python 3 None - , , , , ), break, -, statement (), (), , invalid syntax.

, , , . , - - Python.

0

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


All Articles