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)
有没有办法在一行中写出这样的中断条件?我可能做错了什么吗?
谢谢!
您不能使用三元表达式,因为break
它不是表达式:它不返回值。
虽然,您可以像这样简单地省略换行符。
for val in "string":
if val == "i": break
print(val)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5255 次 |
最近记录: |