fit "break IF condition" statement into one line
Asked Answered
J

4

11

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!

Jeremyjerez answered 11/2, 2019 at 19:7 Comment(1)
You can put the break on the same line as the condition: if val == "i": break.Roughen
L
17

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)
Lonilonier answered 11/2, 2019 at 19:9 Comment(1)
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)Pallid
P
3

This worked for me:

for i in range(10):
  print(i)
  if i == 2: break
Purge answered 11/2, 2019 at 19:13 Comment(0)
C
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.

Carbon answered 11/2, 2019 at 19:16 Comment(0)
P
2

break can't be used in python one liners. If at all you want to minimize the number of lines, You can write as follows:

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

The idea here is: If one line of code ends with colon and if the next line of code doesn't end with colon, these two lines can be typed in to single line without any indentation. (what I mean by 'line of code ends with colon' here is such as def, if, for, while statements)

Consecutive lines with the same indentation can just be separated by a semicolon and can be typed in a single line. (As many as you can if they are consecutive and of the same indentation. But Consider PEP-8 standard)

Politian answered 17/9, 2023 at 2:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.