break expression in inline if – python


Greeting, why is

for number in content:
    if number != 237:

working code, but

for number in content:
    print(number) if number != 237 else break

has an error: expected expression after the inline else?

Asked By: Ruben



this is invalid syntax, to put this into prospective, this is the correct usage of the inline if

for i in range(5):
    foo = 5 if i == 1 else 4

in this code, foo will be assigned the value of 5 or 4, but what about the next code

for i in range(5):
    foo = 5 if i == 1 else break

what will be the value of foo when this code executes ? break returns nothing, its a language statement, so this is invalid syntax.
and your code is exactly the same, it just doesn’t store the result anywhere, it’s still bound to the same syntax rules, and while print(number) actually returns an object in python 3 (a None is a python object), break doesn’t.

Answered By: Ahmed AEK
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.