python觀察日誌(part19)--關於iPython中的In[]和Out[]

學習筆記,僅供參考,有錯必糾


關於iPython中的In[]和Out[]


在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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章