I have a value that starts as None
but should become an int
that gets incremented in a loop. I tried using an inline if to check if it is None and increment otherwise. However the inline if statement throws:
x = None
for _ in range(5):
if x is None:
x = 1
else:
x +=1
print(x)
x= None
for _ in range(5):
x = 1 if x is None else +=1 #SyntaxError: invalid syntax
x +=1 if x is not None else 1 #TypeError unsupported operand type(s) for +=: 'NoneType' and 'int'
print(x)
It works if you don't use the +=
and operator and x explicitly: x = 1 if x is None else x+1
. But I was wandering if or how it is possible to use +=
in an inline if.