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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With