How To Check If A Variable Is Not Null in Python

Check if a variable is not Null

If you are having trouble with the “How to check if a variable is not Null in python” problem and don’t know how to do it, don’t miss our article. We will give you some solutions for checking if a variable is not Null. Read on it.

How to check type of any variable in python?

In Python, we can check the type of any variable by the following command:

type(variable_name)

Example

Input:

integer = 1
print(type(integer))

Output:

<class 'int'>

Input

myDict = {
  "sky": "blue",
  "tree": "green",
  "sun": "yellow"
}
 
print(type(myDict))

Output

<class 'dict'>

To check if a variable is not Null

First, keep your mind that there is no “Null Type” in python, it is “None Type” instead. Now, let’s dive into our article to get some methods to verify whether a variable’s type is None or not

Using “is not” or “ïs” keyword

The result of this method is a boolean type. Look at the following example:

Input:

obj = 'This is a string'
print(type(obj) is not None)

Output:

True

Input:

obj = 'This is a string'
print(obj is None)

Output:

False

Using “==” and “!=” operator

The result of this method also is boolean type:

Input:

obj = 'This is a string'
print(type(obj) == None)

Output:

False

Input:

obj = 'This is a string'
print(obj != None)

Output:

True

Using “if”, “if not” and else statement

The last method to check if a variable is not Null is using if, if not and else statement.

Input:

obj1 = None
obj2 = "String"

if obj1:
  print("obj1 is not None")
else:
  print("obj1 is None")

if not obj1:
  print("obj2 is not None")
else:
  print("obj2 is None")

Output:

obj1 is None
obj2 is not None

Summary

To sum up, in Python, it is None type instead Null type and the condition to check if a variable is not Null is quite simple by using is, is not keyword, operator like != or == and if, if not, else statement.

Maybe you are interested:

Leave a Reply

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