Declaring variables as null or evaluating an expression as null in an if condition (or other cases) is quite common practice as doing programming in different languages.
This is generally done by using the keyword ‘null’.
In other programming languages, for example, this is how you may create a null variable:
In Java:
In PHP:
If you need to evaluate a variable in the if condition, you may check this as follows in Java:
if(myVariable == null) { System.out.println(”Some output”); }
See the examples below for learning how to use the ‘None’ in Python. I will use it in the if statement and a few compound data types.
An example of using none variable in the if statement
First of all, a variable is declared with the none value in the example. After assigning the value, we will check if it is none.
In the if statement, you may use the identity operator ‘is’ as follows:
#A demo of none variable ex_none = None if ex_none is None: print('The value of the variable is none') else: print('Its a not null variable')
The output of the above example is:
Using the == operator example for Python Null
Rather than using the identity operator in the if statement, you may also use comparison operators like ==, !=, etc. for evaluating a ‘none’ value. See the example with the code below where the same code is used as in above example except the comparison operator:
#A demo of none variable with == operator ex_none = None if ex_none == None: print('The value of the variable is none') else: print('Its a not null variable')
The output of this example is the same as in above example.
An example of using None/Null in a Set
In this example, a Python set is created with a few items. The second item is given the ‘None’ value. A for loop is used to display the set items and finally the length of the set is displayed. See the code and output by clicking the link below:
# An example of a set with None set_ex_None = {10,None,30,40,50} for curr_set_item in set_ex_None: print ("The set item:",curr_set_item) print ("The length of set = ",len(set_ex_None))
Output:
You can see, the None is displayed while the length of the set includes the None item as well.
Using None value in a List example
Similarly, you may use the Null value in the compound data type List. Just use the None keyword as in case of sets.
See this example where I have created a list and the third item in the list is None keyword:
# An example of a List with None str_list_None = ['List','with', None, 'Value'] for str in str_list_None: print ("The current list item:",str)
Result: