Why python shell stores last expression in _ variable but python file does not?

Question:

I ran below code in python shell and from a python file, I expected the same output but ironically i get NameError: name '_' is not defined error in python file.

>>> 10+2
12
>>> print(_)
12

So i started wondering why python shell stores last expression in _ variable but it is not even defined in python file.

Asked By: Alireza Bahrami

||

Answers:

In your case you should use the _ variable in the Python interpreter (the Python shell), but not in Python scripts (files with a .py extension). _ is a feature of the Python interpreter and is not available in Python scripts.

In a Python script, you need to explicitly define and assign values to variables if you want to use them. For example, you could modify your code to store the result of the expression in a variable like this:

result = 10 + 2
print(result)
Answered By: di.bezrukov