How does underscore "_" work in Python files?

PythonServer Side ProgrammingProgramming

The underscore (_) is special in Python. There are 5 cases for using the underscore in Python.

1. For storing the value of last expression in interpreter.

The python interpreter stores the last expression value to the special variable called ‘_’.

For example

>>> 12 + 10
>>> _

2. For ignoring the specific values.

The underscore is also used for ignoring the specific values in several languages like elixir, erlang, python, etc. If you don’t need the specific values or the values are not used, just assign the values to underscore.

For example

>>> _, _, a = (1, 2, 3)
>>> a

3. To give special meaning to name of variables and functions.

Variable names with single preceding underscores are used for private variables, functions, classes. Anything with this convention are ignored in from module import *. There are many other conventions you can check out at:

4. To separate the digits of number literal value.

In python, to avoid having to deal with extremely large numbers, you can put underscores to make numbers easily readable.

For example

>>> a = 7_200_000_000   # 7.2 billion easily readable
>>> a

Note that the last feature was added to python in v3.6

Published on 26-Dec-2017 16:45:48