How To Check If A Value Is Zero Or Not None In Python

Check if a Value is Zero or not None in Python

To check if a Value is Zero or not None in Python, we can use 'is' operator and 'is not' operator. Follow the article to better understand.

Check if a Value is Zero or not None in Python

In Python, ‘None’ is a specific object indicating that the object is missing the presence of a value. The Python Null object is the singleton None. In other words, ‘None’ in Python is similar to the ‘Null’ keyword in other programming languages.

To check if a Value is Zero or not None in Python, we have the following ways:

Use ‘is’ operator and ‘is not’ operator

The ‘is’ operator and ‘is not operator is used to compare the memory addresses of two arguments. Everything in Python is an object, and each object has its memory address. The ‘is’ operator checks if two variables refer to the same object in memory.

Example:

  • Create two variables: one equals ‘None’, and one equals 0.
  • Use two operators, ‘is’ and ‘is not, then print the result.
myVar = None
myNumber = 0

if(myVar is None):
    print("myVar is None")

if(myNumber is not None):
    print("myNumber is not None")

Output:

myVar is None
myNumber is not None

Use relational operator ‘==’

The ‘==” operator compares the values ​​of the arguments to see if they are equal.

If equal, the result will be True; otherwise, it will be False.

Example:

  • Create two variables: one equals ‘None’, and one equals 0.
  • Using the ‘is not ‘operator compares the value of value_1 with None. Using the ‘==’ operator compares the value of value_2 with 0. 
  • If the value of value_1 is not ‘None’, it will print ‘value_1 is not None. If the value of value_2 is 0, it will print out ‘value_2 is not None.
myVar = None
myNumber = 0

if myVar is not None:
    print("myVar is not None")

if myNumber == 0:
    print("myNumber is not None")

Output:

value_2 is not None

So we can see the value of myVar is None. The value of myNumber is 0.

Convert to decimal

You can use the way to convert a number to decimal. Of course, if it is ‘None’, then it is impossible. I will use a try/except block to write a program that converts to decimal.

Example:

  • Import module ‘Decimal’.
  • Create a number verify function if it returns about value True and if ‘None’ returns about value False.
from decimal import Decimal

def checkNumber(i):
    try:
        value = Decimal(i)
        return True
    except:
        return False

print(checkNumber(None))
print(checkNumber(0))

Output:

False
True

Summary

If you have any questions about how to check if a value is zero or not None in Python, leave a comment below. I will answer your questions. Thank you for reading!

Maybe you are interested:

Leave a Reply

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