Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying to use if-else expression which is supposed to break the loop if the if condition fails, but getting an invalid syntax error.

Sample code:

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

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

What is wrong in using the break command after the else keyword?

like image 698
Manish Goel Avatar asked Jun 30 '17 14:06

Manish Goel


People also ask

Does Break Break out of if statements Python?

In Python, the break statement provides you with the opportunity to exit out of a loop when an external condition is triggered. You'll put the break statement within the block of code under your loop statement, usually after a conditional if statement.

Does Break Break out of if statements?

breaks don't break if statements. A developer working on the C code used in the exchanges tried to use a break to break out of an if statement. But break s don't break out of if s. Instead, the program skipped an entire section of code and introduced a bug that interrupted 70 million phone calls over nine hours.

What does break do in if else?

The break statement ends the loop immediately when it is encountered. Its syntax is: break; The break statement is almost always used with if...else statement inside the loop.

Why do we need a break in Python?

'Break' in Python is a loop control statement. It is used to control the sequence of the loop. Suppose you want to terminate a loop and skip to the next code after the loop; break will help you do that. A typical scenario of using the Break in Python is when an external condition triggers the loop's termination.


1 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

This is because

print(a) if a > 5 else break

is a ternary operator. Ternary operators are no if statements. These work with syntax:

<expr1> if <expr2> else <expr3>

It is equivalent to a "virtual function":

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

So that means the part next to the else should be an expression. break is not an expression, it is a statement. So Python does not expect that. You can not return a break.

In python-2.x, print was not a function either. So this would error with the print statement. In python-2.x print was a keyword.

You can rewrite your code to:

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

You can read more about this in the documentation and PEP-308.

like image 199
Willem Van Onsem Avatar answered Oct 24 '22 22:10

Willem Van Onsem