<p>如果<code>x</code>为<code>None</code>、<code>False</code>、<code>[]</code>、<code>{}</code>等,则<code>not x</code>为真</p>
<p>除非变量实际上是<code>None</code>,否则<code>x is not None</code>将始终是<code>True</code>。</p>
<p>编辑:</p>
<p>这一点非常重要,只要您想检查变量是否实际设置为正确的值。否则你会遇到麻烦。例如,如果要计算项目列表并执行以下操作:</p>
<pre><code>if not x:
</code></pre>
<p>若要检查是否提供了列表,则条件将在空列表上触发,该列表可能仍然是有效的输入。所以在这种情况下,你想和</p>
<pre><code>if x is not None:
</code></pre>
<p>允许空列表作为有效输入,但仍要检查是否未提供任何列表。</p>
<p>这样的<code>None</code>值与某些语言中的<code>null</code>或<code>nil</code>值相当。它是一个占位符,表示定义的变量中缺少值(如果未定义,它将抛出一个<code>NameError</code>)。这就是为什么在某些情况下,<code>None</code>值被用作默认值的原因:</p>
<pre><code>>>> def foo():
... pass
...
>>> x = foo()
>>> x is None
True
</code></pre>
<p>它还经常用作可选变量的默认值:</p>
<pre><code>>>> def foo(bar=None):
... if bar is None:
... print('No argument passed.')
... else:
... print('Variable bar: %s' % str(bar))
...
>>> foo(0)
Variable bar: 0
>>> foo()
No argument passed.
</code></pre>
<p>这样,<code>0</code>仍然是一个有效值,如果使用<code>if not bar:</code>检查,则该值的计算结果为<code>False</code>。</p>