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!
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With