In writing about this question, it is important to understand a few things , before we step into the code.
Null values appear in almost every programming language, but they can have a different meaning.
A null value basically means it is empty. So when you return a value that is null, it has nothing in it.
Sometimes it can be confused with the value zero, but as zero is an actual integer, it is not an empty value in a field.
Python uses None to define the keyword null, that returns an empty value.
How can we show null in an output?
Lets look at the below output. From observation it can be seen that a,b,d retuns an int value, but that is quite straight forward.
Let’s focus on c. When it is printed out the value on the screen is showing nothing, and its data type is str. But why is that, surely it is None or empty as we were expecting?
Well Python will return as a string , unless it is explicitly declared as empty. The next section will take you through that.
a = 1 b = 1 c = "" d = a-b print(a) print(b) print(c) print(d) print(type(a)) print(type(b)) print(type(c)) print(type(d)) Returns: 1 1 0 <class 'int'> <class 'int'> <class 'str'> <class 'int'>
So based on the above, how do I declare a null value in python?
We have modified the code above, and declared c as None, and in this instance the code now recognises the output as empty.
a = 1 b = 1 c = None d = a-b print(a) print(b) print(c) print(d) print(type(a)) print(type(b)) print(type(c)) print(type(d)) Result: 1 1 None 0 <class 'int'> <class 'int'> <class 'NoneType'> <class 'int'>
What are the other scenarios that None will be returned?
Python also returns values on None, even though they have not been explicitly declared.
In the below if you try to print nothing, it will by default return an empty value.
On the other hand using an if statement you can check if a value is a None.
The final example is where you are using a function, to check if a value is in a list. If the value does not appear in the list it returns nothing.
This is especially handy , if you want to completely sure that that the returned values are nothing.
It gives you a level of comfort that that the code will not pass anything to other parts of the programme.
a = print() print(a) variable = None if variable is None: print("Correct") else: print("Incorrect") variable1 = "today" if variable1 is None: print("Correct") else: print("Incorrect") def returnnone(): list = [1,2,3,4,5] for i in list: if i == 6: print("Six found") else: print(None) returnnone() Result: None Correct Incorrect None None None None None
Click here to get more information on other relevant data analytics posts.