How to check for NULL in Python

In programming languages, the NULL keyword refers to a value representing nothing. It acts as a placeholder value when you need to create a variable without assigning it a value immediately.

In Python, the None value is used in a similar manner to the NULL value:

my_variable = None

This means when you need to check if a variable is NULL in Python, then you need to check if the variable is None.

To check for the variable’s value, you can use the is or equality comparison == operator:

my_variable = None

if my_variable is None:
    print("Variable is NULL")
else:
    print("Not NULL")

The is keyword is used to check if two values refer to the same object. It returns True when the values do point to the same object, or False otherwise.

In this case, the variable and the object indeed point to the None object.

You can also use the equality comparison operator as follows:

my_variable = None

if my_variable == None:
    print("Variable is NULL")

The is keyword is preferred because checking if the variables refer to the same object is faster than asserting if a variable equals to another object.

How to check if the variable is not initialized

In other programming languages such as JavaScript, you can also check for NULL when the variable is defined without any value as follows:

let my_str

if (my_str == null){
    console.log("my_str is NULL")
}

The above code will print the message to the console because an uninitialized variable is equal to null and undefined in JavaScript.

But this doesn’t apply in Python because you can’t declare a variable without assigning any value:

my_str

if my_str is None:
    print("Variable is NULL")

In Python, this will result in NameError:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    my_str
NameError: name 'my_str' is not defined

If you want to assign a value later in Python, you need to initialize the variable with None to prevent this error.

Conclusion

Python uses the None keyword to refer to an empty value instead of NULL, so when you need to check for a NULL value in Python, you check if the variable is None.

You can use the is or == operator to check if a variable equals to None

I hope this tutorial is helpful. Happy coding! 👋

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.