学习笔记,仅供参考,有错必纠
在iPython中,有两个特殊的变量In和Out,它是ipython为方便编辑代码和跟踪执行过程而给出的特殊变量。
现在,我们看下面这段代码,来理解一下这俩变量:
In [1]: x = 2
In [2]: x
Out[2]: 2
In [3]: print("Anhui University of Finance and Economics")
Anhui University of Finance and Economics
In [4]: 'Anhui University of Finance and Economics'
Out[4]: 'Anhui University of Finance and Economics'
In [5]: In[3]
Out[5]: 'print("Anhui University of Finance and Economics")'
In [6]: Out[2]
Out[6]: 2
In [7]: In
Out[7]:
['',
'x = 2',
'x',
'print("Anhui University of Finance and Economics")',
"'Anhui University of Finance and Economics'",
'In[3]',
'Out[2]',
'In']
In [8]: Out
Out[8]:
{2: 2,
4: 'Anhui University of Finance and Economics',
5: 'print("Anhui University of Finance and Economics")',
6: 2,
7: ['',
'x = 2',
'x',
'print("Anhui University of Finance and Economics")',
"'Anhui University of Finance and Economics'",
'In[3]',
'Out[2]',
'In',
'Out']}
In [9]: type(In)
Out[9]: list
In [10]: type(Out)
Out[10]: dict
可以看到,In为列表类型,而Out为字典类型,这可能是因为我们每次都一定会输入一些东西,但是每次的输入不一定都有输出,所以根据列表和字典的特性,In用列表将输入装起来,而Out用字典将输出结果装起来,这样,就可以用代表行号的索引来提取In中的输入记录,用代表行号的键去提取Out中的输出记录,如果某个In没有输出结果,则会报出异常。
现在,我们用下面这段代码证实一下刚才的结论:
In [11]: Out[1] #In[1]没有输出结果,所以Out字典中不存在值为1的键,这样写会报错
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-11-1ed0c57a681f> in <module>()
----> 1 Out[1] #In[1]没有输出结果,所以Out字典中不存在值为1的键,这样写会报错
KeyError: 1