I’m new in python, so if the question is unclear or strange, don’t be surprised.
Accidentally made a typo in the console and came across this. Despite the fact that initially variable _ is not defined, if you do any action before try adding 2+_, then _ is defined as a variable and takes the values of the last action.
>>> 2+_
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '_' is not defined
>>> 2+2
4
>>> 2+_
6
>>> print(_)
4
it doesn’t matter if it’s an arithmetic action or the result of any function. In any case, _ will take any previous value.
>>> print(_)
4
>>> type(_)
<class 'int'>
>>> print(_)
<class 'int'>
>>>
Variables with a different name can’t do this of course
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>> 2+2
4
>>> 2+a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
>>>
And only in the python console. This cannot be done in the file. I’m sorry if the question is stupid, it just got interesting for me to understand why _ takes any previous executed value.
Илья Минин is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.