How To Check If A Variable Is Null In Python

Check if a variable is Null in Python

To check if a variable is Null in Python, there are some methods we have effectively tested: the is operator, Use try/except and the non-equal operator. Follow the article to better understand.

None and Null in Python

Nowaday, the keyword null is used in many programming languages to represent that the pointer is not pointing to any value. NULL is equivalent to 0. A newly created pointer points “miscellaneous” to a particular memory area. Assign the pointer to NULL to make sure it points to 0. Even though 0 is an invalid location, it’s easier to manage than when the pointer points to an area we don’t know.

 In Python, there is no null but None.

None is a specific object indicating that the object is missing the presence of a value. The Python Null object is the singleton None

In other words None in Python is similar to the Null keyword in other programming languages.

Check if a variable is Null in Python

Use the ‘is’ operator

The is operator is used to compare the memory addresses of two arguments. Everything in Python is an object, and each object has its memory address. The is operator checks if two variables refer to the same object in memory.

Example:

myVar = None

# Check variable myVar is Null
if myVar is None:
    print('The value of the variable myVar is None  (null)')

Output:

The value of the variable myVar is None  (null)

In the above example, I declared value = None and then used the is operator to check if value has None or not. If value is valid, then execute the if statement; otherwise execute the else statement.

Note:

Do not use the == operator to check for the value None. Because in some cases will lead to erroneous results.

Use try/except

Use try/except block to check if the variable is None.

Example:

The ‘if’ statement in ‘try’ to check variable ‘value’ exists and the value of ‘value’ is ‘none’

try:
    if myVar is None: 
		print('The value of the variable myVar is None  (null)') # Check name exists
except NameError:
    print("The variable myVar does not exist")

Output:

The variable myVar does not exist

Use the non-equal operator 

Another method to check if a variable is None is using the non-equal or != operator.

Example:

myVar = 1

if myVar != None:
    print('The variable is not null')

Output:

The variable is not null

Summary

Here are ways to help you check if a variable is Null in Python. Or, if you have any questions about this topic, leave a comment below. I will answer your questions.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *