Like we have NUL, NULL, or null in other programming languages, in Python we have None which is used to represent the absence of a value.
In order to check if a particular object is None or not, we can make use of the If condition as below,
-
Syntax 1:
if variable is not None:
Syntax 2:
def function(object):
if object is not None:
# Your code Logic
else:
# Your code Logic
It is always better to look at the PEP (Python Enhancement Proposals) Guides to know what they say.
As per PEP-8
# Correct:
if foo is not None:
# Wrong:
if not foo is None:
Read More: Programming Recommendations
Now let's take a look at a few examples.
def check_for_none(object):
if object is not None:
print(f"The object is: {object}")
else:
print("The object is None!")
check_for_none(42)
check_for_none("Hello")
check_for_none(None)
Output:
The object is: 42
The object is: Hello
The object is None!
Facing issues? Have Questions? Post them here! I am happy to answer!
- Python List of Lists with Examples
- Fix: ERROR: Could not find a version that satisfies the requirement tkinter (from versions: none) ERROR: No matching distribution found for tkinter
- How to Convert Python Notebook .ipynb (JSON) to Executable .py Module
- ModuleNotFoundError: No module named qdarkstyle.colorsystem [Python]
- Python: Pandas Merge Indicator (Left, Right and Both) Example
- Fix: EOFError Exception in Python
- How to URL Decode a Query String in Python
- How to take user input from the console in a Python program
- Compare two lists in Python and return matches
- How to change the Python Default version
- Fix: KeyError: exception in Python
- How to get the Execution Time of A Python Program
- Fix: ModuleNotFoundError: No module named boto3 [Python]
- How to get unique values from a list in Python
- How to pip install Python Modules in VSCode
- Python: Fix - TypeError: NoneType object is not iterable
- How to delete a file using Python code example
- How to create a dictionary comprehension in Python
- Python: Get just the filename without extension using Path
- How to comment out a block of code in Python
- How to add two float numbers in Python
- Python: How to POST Json Data with HTTP Request
- Get MD5 Hash as Checksum of a String in Python
- Python - Convert float to String
- How to Parse XML String in Python
- How to Enable Macros on Excel for Mac - MacOS
- All directional arrows codes for HTML - Html
- PowerShell on Mac: The term get-service is not recognized as a name of a cmdlet, function, script file, or executable program - Powershell
- Change TextEdit File Encoding - MacOS
- How to change the Python Default version - Python
- Step-by-Step Guide: How to Fix - Error Establishing a Database Connection in WordPress - PHP
- Write javaScript code in Swedish using FikaScript - JavaScript
- [JEP 430] Java JDK 21 New Feature - String Templates (Preview) - Java-JDK-21