Understanding the NoneType object in Python

Just like other programming languages like C, C++, and Java, Python also has null objects and variables. If you have heard about C or Java, you would have also heard about the null concept. It is used to define:

  • A null pointer.
  • Empty variable.
  • When parameters are not assigned.

Similarly, Python uses the None keyword to define null objects and variables. This keyword is an object in Python.

Using Python’s None keyword

Generally, we use None for comparison and to find a certain match. First, we import the re library and use the “re.match” function to check a certain value is matching with the given string whether it matches or not.

Below is the python code for checking that pattern “Paris” matches the given string. Here we are importing the re library as using the “re.match” function for comparison.

# Using None to test pattern matches

import re
match_1 = re.match(r"Paris", "Hello, World!")

if match_1 is None:
     print("It doesn't match.")

Output:

It doesn't match.

Here we are using the None keyword to check the pattern “Paris” is matching with the string “Hello, World!” or not.

Understanding Null in Python

When there is no return statement in the function, the function returns the None value. It means when you don’t use the “return” statement in the function you will not see any output on the console. However, you print a call to it so that you will be able to see “None” in return.

def with_no_return():
    pass
with_no_return()

print(with_no_return())

Output:

None

Note: “None” appears so frequently as a return value that it will not print “None” on the console. You have to give a command for Python to print it.

You can also refer to this linkĀ How to check if a string is Null in Python to know further about how to check if a string is null or not.

Leave a Reply

Your email address will not be published.