In other high-level programming languages such as Java, C and C++ we have the concept of null. There null is used to represent or point empty value or no value at all. But in Python, we do not have null instead we use the None keyword which is pretty similar to the concept of null.
Python None keyword
In Python, we use the None keyword to define no value or null objects. In other languages null is also defined as 0 but in Python, we can not define 0 as None, because "None" itself a separate object in Python.
>>> type(None) <class 'NoneType'>
How to Declare of Null or None variable in Python
In static languages, we need to declare a variable before initialisation. But Python is a dynamic language, so here we do not have the concept of variable declaration In Python, we can directly initialise or assign a value to the variable. In Python, if we try to access a variable before initialisation, then the interpreter thrown an error "name not defined" .
#accessing a variable before initializaiton >>> print(a) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'a' is not defined
>>> a = None >>> print(a) None
<Note>: In Python, a variable will occupy space or come in existence when a value is assigned to it, but in a static language, a variable comes in existence when it is declared.
null or Python None with Functions
If a function does not have a return statement, then it returns None object.
def add(): a = 2 + 3 # print the return value of add() function print(add())
Here you can see that there is no return statement in the
function so the function returns no value or None.
<Note> Python print() function also return None.
Use Python None value
is used in comparison statements. One of the primary examples is when we want to check if the result is
def add(): a = 2 + 3 result = add() if result == None: print("Function add() returns no value")
Function add() returns no value
None as Falsy
is treated as False value like 0 or False, which means if the statement reads None as a False value. There are many other falsy objects, such as:
- Empty list
- Empty dictionary
- Empty set
- Empty string
if None: print("The statement is True") else: print("The statement is False")
The statement is Flase
The above example is similar to
if False: print("The statement is True") else: print("The statement is False")
The statement is False
- None is a keyword that represents no value.
- If a function has no return statement than it returns None by default.
- In Python None treated as a false value.
People are also reading:
- Python Frameworks
- Best Way to Learn Python
- Python Operators
- How To Make a Game With Python?
- Enumerate in Python
- Flatten List & Lists of List in Python
- Convert List to Dictionary in Python
- What can you do with Python?
- How to Remove Last Character from a Python String?
- Python 3.10 Switch Case Statement