擅长:python、mysql、java
<p>您已经找到了<a href="https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator">ternary operator</a>,在Python中称为<a href="https://www.python.org/dev/peps/pep-0308/" rel="nofollow noreferrer">Conditional Expression</a>。表达式<code>x if condition else y</code>表示如果条件(可以是复杂语句或函数)的计算结果为True,则表达式返回<code>x</code>,如果条件的计算结果为False,则表达式返回<code>y</code>。在</p>
<p>它的工作方式类似于以下if语句:</p>
<pre><code>if test1:
if test2:
print(x)
else:
print(y)
</code></pre>
<p>错误源于没有将<a href="https://docs.python.org/3/library/functions.html#print" rel="nofollow noreferrer">print function</a>参数包装在括号中。这是对Python3的一个更改,而在Python2中,您的语法应该是很好的。重写如下:</p>
<p><code>if test1: print(x if test2 else y)</code></p>
<p>你的错误就会消失。在</p>