Why does typing _ in the Python interpreter return True? [duplicate]

女生的网名这么多〃 提交于 2019-12-11 02:22:20

问题


I am getting very weird interpreter behaviour:

>>> _
True
>>> type(True)
<class 'bool'>
>>> type(_)
<class 'bool'>

I tried this because _ came up as a suggestion in Bpython, but it seems to work in the normal interpreter too. I am using

Python 3.3.3 (v3.3.3:c3896275c0f6, Nov 16 2013, 23:39:35) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin

Can anybody explain why _ is a substitute for True? Is it legacy, similarly to how ";" can be used to end commands, but is not necessary/encouraged?

EDIT: It seems to be random. This does not happen in a new terminal, but once I start working on something _ starts becoming true. What the hell is going on?


回答1:


_ will be the result of the last evaluated command - at interpreter start up there isn't any so you'll get a NameError... after that, you'll get the previous result... Try opening a new interpreter and doing 2 + 2... you'll see 4 returned, then type _... eg:

>>> _

Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    _
NameError: name '_' is not defined
>>> 2 + 2
4
>>> _
4



回答2:


2 + 1
Out[19]: 3

_ + 3
Out[20]: 6

_ stores the last returned value. Try it out.




回答3:


_ simply gives you the last result evaluated (in the REPL, not in an ordinary script). This can also mysteriously prevent objects from being deleted immediately.




回答4:


_ in the interactive interperter is usually the last output you received.

>>> 1 + 1
2
>>> _
2

Note it only applies to outputs (printed data won't do).



来源:https://stackoverflow.com/questions/22269897/why-does-typing-in-the-python-interpreter-return-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!