I only want to place None numerically as 0 such as 1+None=1. What should I do?If 1+None=1 is established even if it cannot be placed as 0.
python
Is it like this?
def Add(x,y):
return(x if x else0)+(y if y else0)
print(Add(10,1))#11
print(Add(10, None))#10
print(Add(None,1))#1
print(Add(None, None))#0
Python should not be able to do it.
+
operator runs __add__
on the left or _radd__
on the right1+None
, both sides are int
and NoneType
_add__
+
in this expressionOnce you have your own type, you can change the behavior of +
for that type.
Example:
class N(int):
def__add__(self, other):
if other==None:
other = 0
return N(super().__add__(other))
def__radd__(self, other):
return self.__add__(other)
n0 = N(0)
n1 = N(1)
n2 = N(2)
print(f"{n1+None=}")#1
print(f"{None+n1=}")#1
print(f"{n1+2=}")#3
print(f"{1+n2=}")#3
print(f"{n1+n2=}")#3
print(f"{n0+1+None=}")#1
If you want to complete it properly, you need to define other methods to emulate the numeric type.SymPy and others are such approaches.
There is no way to avoid the unsupported operand type(s) for +: 'int' and 'NoneType'
exception when using the +
operator for None, and it will require some redundancy like the other answers.
By the way, there is also a way to get 0 using the or operator, such as None or 0
.
x,y=1,None
Returns print((x or 0)+(y or 0))#1
© 2025 OneMinuteCode. All rights reserved.