1

Can someone explain what happened in the second run ? Why did I get a stream of 9's when the code should have given an error?


>>> for __ in range(10): #first run
...     print(__)
...
0
1
2
3
4
5
6
7
8
9

This was the second run

>>> for __ in range(10): #second run
...     print(_)
...
9
9
9
9
9
9
9
9
9
9
>>> exit()

After this, when I ran the code for the third time, the same code executed as expected and gave the below error. I realize that this question has no practical use. But, I would really like to know why it happened?

NameError: name '_' is not defined

1 Answer 1

5

The _ variable is set in the Python interpreter, always holding the last non-None result of any expression statement that has been run.

From the Reserved Classifiers and Identifiers reference:

The special identifier _ is used in the interactive interpreter to store the result of the last evaluation; it is stored in the builtins module.

and from sys.displayhook():

If value is not None, this function prints repr(value) to sys.stdout, and saves value in builtins._. [...] sys.displayhook is called on the result of evaluating an expression entered in an interactive Python session.

Here, that result was 9, from an expression you must have run before the code you shared.

The NameError indicates you restarted the Python interpreter and did not yet run an expression statement yet that produced a non-None value:

>>> _
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '_' is not defined
>>> 3 * 3
9
>>> _
9
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.