Null value is used in many programming languages but in Python, Null value does not exist. Instead of Null, the “None” is used in Python. The None value in Python indicates the absence of a value, and the values “0”, false, empty string, etc., do not represent “None”. In Python, there are various methods to verify if a variable is Null or not.
This write-up will provide a detailed guide for checking if a variable is Null in Python using the following methods:
So, let’s get started!
Method 1: Using “is” Operator
“is” operator is used in the below-given Python program to check if the variable is none/null.
Code:
val = None
if val is None:
print('Input variable is null')
if val is not None:
print('Input variable is not null')
In the above code:
- A variable named “val” is assigned the “None” value.
- The “is” operator is used with the if statement to check if the variable’s value is null or not.
- The “is” operator will retrieve true if the value of variable “val” is equal to “None”. In such a case, the first if will be executed.
- If both the right and left sides of the “is” operator are unequal, then the second if block will be executed.
Output:
The above output shows that the variable’s value equals “None”.
Method 2: Using “==” Operator
In the example code given below, the “==” operator is utilized to verify if a variable is equal to None or not.
Code:
val = None
if val == None:
print('Input variable is null')
if val != None:
print('Input variable is not null')
In the above code:
- By using the “==” operator, it can be determined whether the given condition is equal to None.
- If the value is equal to None, then the statement written in the first “if” block will be executed; otherwise, the second “if” block will be run.
Output:
The above output verified that the input variable is Null/None.
Method 3: Using “if-else” Statement
In the example code given below, a simple “if-else” statement is used to check if the variable is Null or not:
Code:
val = None
if val:
print('val is not None')
else:
print('val is None')
In the above code snippet:
- The simple “if-else” statement is utilized to check if the variable’s value is “None”.
- The if-block will execute if the variable’s value is not equal to none.
- If the input variable is assigned with a None value, then the “else” block will execute.
Output:
The above output verified that the input variable’s value is “None”.
That’s it from this Python tutorial!
Conclusion
The “is” and “is not” operators, “==” and “!=” operators and “if-else” Statements are used to check if the variable is “Null/None” in Python. The “is” and “is not” operators are used along with the combination of the “if” statement to check the Null/None variable in Python. The “==” operator also works similarly to the “is” operator in Python, i.e., to check the Null variables. This article presented a detailed guide on how to check if a variable is Null in Python with numerous examples.