47

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).

Jamgreen
  • 10,329
  • 29
  • 113
  • 224

5 Answers5

75

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
17

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

if number or number==0:
    return True
Amey Jadiye
  • 3,066
  • 3
  • 25
  • 38
2

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

1

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

DanP
  • 21
  • 3
0

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!)
Saiteja Parsi
  • 412
  • 1
  • 5
  • 15