Python - How To Check if a Variable Is None in Python

ID : 221

viewed : 210

Tags : PythonPython Variable

vote vote

92

A variable can store different values in Python. It can have integer, character, float, and other values. The None is a special keyword in Python. It does not mean that the value is zero, but the value is NULL or not available. None is a special object. Its type is called NoneType.

We sometimes encounter an exception that a variable is of NoneType. So we should know how to check if a variable is None or not.

In this tutorial, we will test if a variable is of type None in Python.

Use the is Keyword to Check if a Variable Is None in Python

The if statement can check for a condition in Python. To check whether a variable is None, we can use the is keyword. This keyword checks whether two variables refer to the same object.

For Example,

a = None b = 5  if(a is None):     print("A is None")      if(b is not None):     print("B is not None") 

Output:

A is None B is not None 

Use the isinstance() Function to Check if a Variable Is None in Python

The isinstance() function can check whether an object belongs to a certain type or not. We can check if a variable is None by checking with type(None).

It returns a tuple, whose first element is the variable whose value we want to check. The second element is True or False, whether the variable matches the required type or not.

For example,

a = None b = 5  print((a, isinstance(a, type(None))))     print((b, isinstance(b, type(None)))) 

Output:

(None, True) (5, False) 

Use a Dictionary to Check if a Variable Is None in Python

A dictionary stores key-value pairs in Python. We can use it to check if a variable is None or not. This method is unconventional, but it provides the desired result.

See the code below.

a = None dict = {None: 'The variable is None'}      print(dict[a]) 

Output:

The variable is None 

Use the try and except Block to Check if a Variable Is None in Python

The try...except block help in dealing with code that may raise exceptions. As discussed earlier, if Python detects a variable that is None and is operated on, it may raise the NoneType exception.

We can work on our code with the variable we suspect is None in the try block, and if the variable is None, then the exception will be raised, which is caught in the catch block.

a = None b = 5 try:     c = a + b except:     print("Some variable is None") 

Output:

Some variable is None 

  • Related HOW TO?