How to Check for Not None in Python Programming


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


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!
None Check in Python Examples

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright ยฉ Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap