As per the official python tutorial,
In interactive mode, the last printed expression is assigned to the variable _. This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations, for example:
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06
This variable should be treated as read-only by the user. Don’t explicitly assign a value to it — you would create an independent local variable with the same name masking the built-in variable with its magic behaviour.
There are no confusions here.
Then I saw some people using _ as a loop variable. For example, as per this blog post:
_ is used as a throw-away name. This will allow the next person reading your code to know that, by convention, a certain name is assigned but not intended to be used. For instance, you may not be interested in the actual value of a loop counter:
n = 42
for _ in range(n):
do_something()
Is this a good convention? I verified in the interpreter that using _ in loop masks the built-in variable afterwards. But is it okay to use it as a loop variable when it is used in scripts (ie. not in interactive mode)
ntimes and do not need to bother or use the looping variable.