ipython 行号乱序导致 NameError

ipython line number out of order creates NameError

我的浏览器中有一个 ipython 笔记本 运行,我有一个 'x' 的 NameError,它在笔记本的正上方定义,但数值较低行号,我认为这是 NameError 的原因。

例如,它看起来像这样:

In [12]: x = np.random.random((3, 4))
In [4]: print x

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-2-73c1d467e5a9> in <module>()
      1 #your code here
----> 2 print x

NameError: name 'x' is not defined

如何确定这里的执行顺序?

左边的数字只是表示代码块的执行顺序。

根据您运行每个单元格的方式,数字会发生变化。在示例中,您只需 运行 [12] 然后 [4] 将更改为 [13]。 x 将打印。

顺序由您决定。但是,在顶部栏上,您可以单击 运行 全部,这将 运行 所有块自上而下。

为了避免混淆和已经定义的变量。我建议定期重新启动 IPython 内核(还有顶部栏),然后 运行 全部。