将“break IF condition”语句放入一行

Dom*_*aul 5 python for-loop break python-3.x

我想写一个语句,如果满足某个条件,则跳出 for 循环,但在一行中。

我知道这有效:

for val in "string":
    if val == "i":
        break
    print(val)
Run Code Online (Sandbox Code Playgroud)

我知道有效:

value_when_true if condition else value_when_false
Run Code Online (Sandbox Code Playgroud)

但是当我运行这段代码时,我收到了一个语法错误:

break if some_string[:5] == condition
Run Code Online (Sandbox Code Playgroud)

有没有办法在一行中写出这样的中断条件?我可能做错了什么吗?

谢谢!

Oli*_*çon 8

您不能使用三元表达式,因为break它不是表达式:它不返回值。

虽然,您可以像这样简单地省略换行符。

for val in "string":
    if val == "i": break
    print(val)
Run Code Online (Sandbox Code Playgroud)