Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fit "break IF condition" statement into one line

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!

like image 586
Dominique Paul Avatar asked Feb 11 '19 19:02

Dominique Paul


2 Answers

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)
like image 152
Olivier Melançon Avatar answered Oct 31 '22 12:10

Olivier Melançon


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.

like image 40
mad_ Avatar answered Oct 31 '22 11:10

mad_