Check if value is zero or not null in python

Question:

Often I am checking if a number variable number has a value with if number but sometimes the number could be zero. So I solve this by if number or number == 0.

Can I do this in a smarter way? I think it’s a bit ugly to check if value is zero separately.

Edit

I think I could just check if the value is a number with

def is_number(s):
    try:
        int(s)
        return True
    except ValueError:
        return False

but then I will still need to check with if number and is_number(number).

Asked By: Jamgreen

||

Answers:

If number could be None or a number, and you wanted to include 0, filter on None instead:

if number is not None:

If number can be any number of types, test for the type; you can test for just int or a combination of types with a tuple:

if isinstance(number, int):  # it is an integer
if isinstance(number, (int, float)):  # it is an integer or a float

or perhaps:

from numbers import Number

if isinstance(number, Number):

to allow for integers, floats, complex numbers, Decimal and Fraction objects.

Answered By: Martijn Pieters

Zero and None both treated as same for if block, below code should work fine.

if number or number==0:
    return True
Answered By: Amey Jadiye

You can check if it can be converted to decimal. If yes, then its a number

from decimal import Decimal

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

print is_number(None)   // False
print is_number(0)      // True
print is_number(2.3)    // True
print is_number('2.3')  // True (caveat!)
Answered By: Saiteja Parsi

The simpler way:

h = ''
i = None
j = 0
k = 1
print h or i or j or k

Will print 1

print k or j or i or h

Will print 1

Answered By: Luciano Pinheiro

DO NOT USE:

if number or number == 0:
    return true

this will check "number == 0" even if it is None.
You can check for None and if it’s value is 0:

if number and number == 0:
    return true

Python checks the conditions from left to right:
https://docs.python.org/3/reference/expressions.html#evaluation-order

Answered By: DanP
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.