None in Python is used for defining null variables and objects. None is an instance of the NoneType class.
This class is a singleton, meaning that there can be only one instance of it. In fact, all the variables assigned to none, point to the same object in Python.
Working with None in Python
We will verify this later in the tutorial and learn lots more about None in Python.
1. Declaring and Assigning None in Python
Let’s start by declaring a variable and assigning it to None. Run the following line of code in your python notebook.
1 |
a = None |
Now we can go ahead and print the value of the variable.
1 |
print(a) |
Output :
1 |
None |
We get ‘None’ as the output.
2. Printing the ‘Type’ of a variable assigned to None in Python
What do you think should be the type of a variable assigned to None?
Let’s print it out using the following line of code :
1 2 |
a = None print(type(a)) |
We get the output as :
1 |
<class 'NoneType'> |
This is in accordance with what we discussed above. A variable assigned to None in Python points to an instance of ‘NoneType’ class.
There is only one instance of the NoneType class, therefore all the variables set to null point to the same object.
In fact, we can compare the IDs of two different variables set to None.
1 2 3 4 5 |
a = None b = None print(id(None)) print(id(a)) print(id(b)) |
Output :
1 2 3 |
10306432 10306432 10306432 |
We can see that None, a and b have the same object IDs.
3. Comparing a variable set to None with None
Let’s use the ‘==‘ and ‘is‘ operator to compare a variable set to None with None.
1 2 3 |
a = None print(a==None) print(a is None) |
Output :
1 2 |
True True |
You can also use None as a condition in if statements. Let’s see how to do that.
4. Using None in Python with Conditional Statements
Let’s use variables set as None in If conditions.
1 2 3 4 5 |
a = None if (a) : print("Condition is true") else : print("Condition is false") |
Output :
1 |
Condition is false |
We can see that a variable set as None works as false. We can use this to check for variables that are set to None in our programs.
You can also use the condition with a ‘not‘.
1 2 3 |
a = None if (not a) : print("Not none means true") |
Output :
1 |
Not none means true |
5. Returning None from a function
When we don’t set a return value for a function then None is the default return type.
We can verify this with the following piece of code :
1 2 3 4 5 6 |
def fun() : print("Hello World") a = fun() print(a) print(id(a)) print(type(a)) |
Output :
1 2 3 4 |
Hello World None 10306432 <class 'NoneType'> |
The ID in the output is same as the IDs that were printed above.
Conclusion
This brief tutorial was about None in Python. We established that all variables set to None point to the same instance of NoneType class. We also covered how to use None datatype as a condition in If statements. Hope you had fun learning with us!