Horje
How to check NoneType in Python

The NoneType object is a special type in Python that represents the absence of a value. In other words, NoneType is the type for the None object, which is an object that contains no value or defines a null value. It is used to indicate that a variable or expression does not have a value or has an undefined value. “None” basically means the absence of a value.

In this article, we are going to discuss methods for how to check NoneType in Python along with proper steps and outputs.

Check NoneType in Python

Below are some ways by which we can check the NoneType in Python:

Python Check NoneType Using ‘is’ Operator

In this example, the is operator is used to check whether a variable is of None type. If the x is None, then it will print x along with its type as shown in the output, else it will print the else statement “X is not None”.

Python3

x = None
 
if x is None:
    print(x)
    print(type(x))
else:
    print("X is not None")

Output

None
<class 'NoneType'>

Python Check None Using Assignment Operator (==)

In this example, the code checks if the variable x is equal to None using the equality (==) operator and prints a corresponding message. If x is None, it prints “The result is None“; otherwise, it prints “The result is not None.”

Python3

x = None
 
# using assignment operator
if x==None:
    print("The result is None")
else:
    print("The result is not None")

Output

The result is None

Check Python None Type Using type() Method

In this example, the code employs the type() method to check if the variable x is of type NoneType. It prints “The variable is of NoneType.” if x is None; otherwise, it prints “The variable is not of NoneType.”

Python3

x = None
 
# Using type() method
if type(x)==type(None):
    print("The variable is of NoneType.")
else:
    print("The variable is not of NoneType.")

Output

The variable is of NoneType.

Check Python None Using if Condition

In this example, the code uses an if condition with the value None, which is considered as False in a boolean context. Therefore, it executes the else block and prints the value which is 10.

Python3

# Using if condition
if None:
  print(0)
else:
  print(10)

Output

10




Reffered: https://www.geeksforgeeks.org


Geeks Premier League

Related
How To Convert Generator Object To Dictionary In Python How To Convert Generator Object To Dictionary In Python
Different Appium Scroll Strategies Different Appium Scroll Strategies
Remove URLs from string in Python Remove URLs from string in Python
What is Math in JavaScript? What is Math in JavaScript?
Indian Partnership Act, 1932: Meaning, Essential Requirements and Kinds Indian Partnership Act, 1932: Meaning, Essential Requirements and Kinds

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12