Home > Software engineering >  break expression in inline if - python
break expression in inline if - python

Time:09-18

Greeting, why is

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

working code, but

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

has an error: expected expression after the inline else?

CodePudding user response:

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.

  • Related