Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling None when adding numbers

I would like to perform addition of 2 integers, which can also be None, with the following results:

add(None, None) = None
add(None, b) = b
add(a, None) = a
add(a, b) = a + b

What is the most pythonic, concise expression for this? So far I have:

def add1(a, b):
    if a is None:
        return b
    elif b is None:
        return a
    else:
        return a + b

or

def add2(a, b):
    try:
        return a + b
    except TypeError:
        return a if a is not None else b

Is there any shorter way to achieve it?

like image 549
michailgames Avatar asked Nov 16 '17 10:11

michailgames


People also ask

Can I add None in Python?

In Python, None keyword is an object, and it is a data type of the class NoneType . We can assign None to any variable, but you can not create other NoneType objects. Note: All variables that are assigned None point to the same object. New instances of None are not created.

What does the None mean in Python?

The None keyword is used to define a null value, or no value at all. 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.

Is None== None in Python?

None is a singleton object (there only ever exists one None ). is checks to see if the object is the same object, while == just checks if they are equivalent. But since there is only one None , they will always be the same, and is will return True.

How do you remove None from output in Python?

The None is passed to the print on that last line and is printed. Alternatives: Don't print the search on the last line, just call search (with no print surrounding). Don't print from the search function.


1 Answers

This is reasonably compact and can handle different numbers of terms:

def None_sum(*args):
    args = [a for a in args if not a is None]
    return sum(args) if args else None 
like image 157
Paul Panzer Avatar answered Sep 23 '22 03:09

Paul Panzer