python-三元运算符的语法错误
作者:互联网
我是Python的新手,正在尝试使用具有这种格式的三元运算符(我认为是)
value_true if <test> else value_false
这是一段代码:
expanded = set()
while not someExpression:
continue if currentState in expanded else expanded.push(currentState)
# some code here
但是Python不喜欢它,并说:
SyntaxError: invalid syntax (pointed to if)
如何解决?
解决方法:
python中的三元运算用于表达式,而不是语句.表达是有价值的东西.
例:
result = foo() if condition else (2 + 4)
# ^^^^^ ^^^^^^^
# expression expression
For语句(代码块,例如continue,for等)在以下情况下使用:
if condition:
...do something...
else:
...do something else...
你想做什么:
expanded = set()
while not someExpression:
if currentState not in expanded: # you use set, so this condition is not really need
expanded.add(currentState)
# some code here
标签:python,ternary-operator 来源: https://codeday.me/bug/20191011/1894026.html