
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How does underscore "_" work in Python files?
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 22 >>> _ 22
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
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: https://hackernoon.com/understanding-the-underscore-of-python-309d1a029edc
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 7200000000
Note that the last feature was added to python in v3.6
- Related Articles
- What does double underscore prefix do in Python variables?
- Underscore(_) in Python
- How does garbage collection work in Python?
- How does class inheritance work in Python?
- How does issubclass() function work in Python?
- How does isinstance() function work in Python?
- How does Overloading Operators work in Python?
- How does tuple comparison work in Python?
- How does ++ and -- operators work in Python?
- How does variable scope work in python?
- How does Python while loop work?
- How does a Python interpreter work?
- How does variable scopes work in Python Modules?
- How does [d+] regular expression work in Python?
- How does B regular expression work in Python?
