10

I want to write a statement that breaks out of a for-loop if a certain condition is fulfilled, but in one line.

I know that this works:

for val in "string":
    if val == "i":
        break
    print(val)

and I know that this works:

value_when_true if condition else value_when_false

but when I run this piece of code I get a syntax error:

break if some_string[:5] == condition

Is there a way to write such a break condition in one line? Am I maybe doing something wrong?

Thanks!

Dominique Paul
  • 1,623
  • 2
  • 18
  • 31

3 Answers3

15

You cannot use a ternary expression because break is not an expression; it does not return a value.

Although, you can simply omit the line break like this:

for val in "string":
    if val == "i": break
    print(val)
Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
  • Also, this is not good practice enough to be part of the answer, but you can have fun and do `for val in takewhile('i'.__ne__, "string"): print(val)` – Olivier Melançon Feb 11 '19 at 19:21
3

This worked for me:

for i in range(10):
  print(i)
  if i == 2: break
Anadactothe
  • 170
  • 1
  • 9
3

There is no harm in writing below code

for val in "string":
    if val == "i":
        break

One-liners do not bring any good but all the operations are squashed in a single line which is hard to read.

value_when_true if condition else value_when_false This is only good if you have an expression. For example

x = 1 if True else 0

As break is not an expression it cannot be used in like above

if condition: break will break the loop. But again I would suggest to have your original code in place as it is more readable.

mad_
  • 8,121
  • 2
  • 25
  • 40