三元运算符语法错误

3

我是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)

如何解决这个问题?
1个回答

12

在Python中使用三元运算符需要使用表达式,而不是语句。表达式是具有值的东西。

例如:

result = foo() if condition else (2 + 4)
#        ^^^^^                   ^^^^^^^
#      expression               expression

对于语句(如 continuefor 等代码块),请使用 if

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

2
顺便提一下,not x in y = x not in y - user395760
如果是这样的话,那么三元操作中就不应该使用 print - Ashwini Chaudhary
据我理解,您实际上不需要使用 continue。只需将 "一些代码" 添加到 if 块中,并将其添加到 expanded 中(请参见我的代码的最后一行)。 - defuz
@defuz,从你的回答中我理解到Python不擅长三元运算符,是吗? - megas
1
@megas,再次提醒,对于表达式:one if condition else two。对于语句:if condition: do_something() - defuz
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接