2

I'm using Python 3.6. I noticed that the following is not allowed:

while something:

    # do something

    # This is an invalid syntax
    break if condition else pass

Since conditional expressions are allowed since v2.5, why is this usage not permitted?

Community
  • 1
  • 1
Gabriel
  • 40,504
  • 73
  • 230
  • 404

3 Answers3

4

Ternary operator require expressions while both break and pass are statements.

Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93
1

The answer to your question is that break is a statement, not an expression. Python's developers explicitly decided that they didn't want Python to be an expression-based language, hence the syntax error with your construct. As @Dmitry points out, there is no way to avoid having a break statement.

holdenweb
  • 33,305
  • 7
  • 57
  • 77
  • Though if all you need to do is break then it's permissible (though of questionable style) to write `if condition: break` on a single line. At present, however, vertical whitespace doesn't appear to be in short supply. – holdenweb Mar 10 '17 at 17:48
0

Use this way:

while something:

    if condition:
        break
    else:
        ...

Note ternary conditional operator does not work with python statements.

Dmitry
  • 2,026
  • 1
  • 18
  • 22
  • Sorry if I wasn't clear on the other Python question. I didn't mean to imply you copied my answer, just that your answer came later than mine, and didn't bring any new value. Thank you for deleting it. Note that I didn't downvote your answer (that's why I left a comment), and downvoting my answer hurts your reputation more than mine. Best regards, Eric – Eric Duminil Mar 13 '17 at 14:31
  • 1
    @EricDuminil I provided my own code and did not look at other answers. there is no difference for me that they suppose. I think it is user prerogative to evaluate answers. I have canceled my downvote and vote up for you answer. Best Wishes, Dmitry. – Dmitry Mar 13 '17 at 15:29