The concept of a
null keyword is that it gives a variable a neutral, or “null” behaviour.
Python’s null Equivalent: None
The equivalent of the
null keyword in Python is
None. It was designed this way for two reasons:
- Many would argue that the word “null” is somewhat esoteric. It’s not exactly the most friendliest word to programming novices. Also, “None” refers exactly to the intended functionality – it is nothing, and has no behaviour.
- In most object-oriented languages, the naming of objects tend to use camel-case syntax. eg.
ThisIsMyObject. As you’ll see soon, Python’s
Nonetype is an object, and behaves as one.
Checking if a Variable is None
There are two ways to check if a variable is
None. One way can be performed by using the
is keyword. Another is using the
== syntax. Both comparison methods are different, and you’ll see why later:
null_variable = Nonenot_null_variable = ‘Hello There!’# The is keywordif null_variable is None:print(‘null_variable is None’)else:print(‘null_variable is not None’)if not_null_variable is None:print(‘not_null_variable is None’)else:print(‘not_null_variable is not None’)# The == operatorif null_variable == None:print(‘null_variable is None’)else:print(‘null_variable is not None’)if not_null_variable == None:print(‘not_null_variable is None’)else:print(‘not_null_variable is not None’)
This code will give us the following output:
null_variable is Nonenot_null_variable is not Nonenull_variable is Nonenot_null_variable is not None