Let’s understand what does Python null mean and what is the NONE type. In many programming languages, ‘null‘ is used to denote an empty variable, or a pointer that points to nothing. ‘null’ basically equals 0. Whereas in Python, there is no ‘null’ keyword available. Instead, ‘None‘ is used, which is an object, for this purpose.
What is Python null?
Whenever a function doesn’t have anything to return i.e., it does not contain the return statement, then the output will be None.
In simpler words, None keyword here is used to define a null variable or object. None is an object , and a data type of class NoneType.
def func_no_return() a = 5 b = 7 print(func_no_return()) None
Whenever we assign None to a variable, all the variables that are assigned to it point to the same object. No new instances are created.
In Python, unlike other languages, null is not just the synonym for 0, but is an object in itself.
type(None) <class 'NoneType'>
Declaring null variables in Python
Null variables in python are not declared by default. That is, an undefined variable will not be the same as a null variable. To understand, all the variables in python come into existence by assignment only. Have a look at the code below :
The above code shows the difference between an undefined variable and a None variable.
How to check if a variable is none in Python?
You can check whether a variable is None or not either using ‘ is ‘ operator or ‘ == ‘ operator as shown below
- Using the ‘is’ operator
#declaring a None variable a = None if a is None : #checking if variable is None print("None") else : print("Not None")
The above code will give None as output.
- Using the ‘==’ operator
#declaring a None variable a = None if (a == None) : #checking if variable is None print("The value of the variable is None") else : print("The value of variable is Not None")
The above code gives The value of variable is None as output.
To conclude, the points to remember are:
- None keyword is used to define a null variable.
- None is not same as 0.
- None is of an immutable type.
- And None can be used to mark missing values and also default parameters.