三元运算符的语法错误 [英] Syntax error with ternary operator

查看:48
本文介绍了三元运算符的语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,我正在尝试使用具有这种格式的三元运算符(我想是这样)

I'm new to Python and I'm trying to use ternary opertor which has this format (I think so)

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不喜欢它并说:

But Python doesn't like it and says:

SyntaxError: invalid syntax (pointed to if)

如何修复它?

推荐答案

Python中用于的三元运算表达式,而不是声明。表达式是有价值的东西。

Ternary operation in python using for expression, not statements. Expression is something that has value.

示例:

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

对于语句(如 continue for 之类的代码块) ,等等)使用 if

For statements (code blocks such as continue, for, etc) use 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

这篇关于三元运算符的语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆