Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if value is zero or not null in python

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

like image 833
Jamgreen Avatar asked Jan 29 '15 08:01

Jamgreen


People also ask

IS null or == null Python?

There's no null in Python; instead there's None . As stated already, the most accurate way to test that something has been given None as a value is to use the is identity operator, which tests that two variables refer to the same object.

How do you check if a value is not None in Python?

Use the is not operator to check if a variable is not None in Python, e.g. if my_var is not None: . The is not operator returns True if the values on the left-hand and right-hand sides don't point to the same object (same location in memory).

Is not equal to null in Python?

Python if not equal to null In Python, there is None instead of Null. So we have to check if a variable contains a None value or not. There are different ways to check it. In the above code, we are comparing the variable with the None value.

Is None and 0 same in Python?

None is not the same as 0, False, or an empty string. None is a data type of its own (NoneType) and only None can be None.


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

like image 69
Martijn Pieters Avatar answered Oct 16 '22 20:10

Martijn Pieters


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

if number or number==0:
    return True
like image 28
Amey Jadiye Avatar answered Oct 16 '22 19:10

Amey Jadiye


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

like image 2
Luciano Pinheiro Avatar answered Oct 16 '22 19:10

Luciano Pinheiro