0

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.

Finn
  • 2,333
  • 1
  • 10
  • 21

1 Answers1

0

You are using the inline code properly with x = 1 if x is None else x+1, you can't use += in inline. To understand, let's add some parenthesis without affecting code:

x = None
for _ in range(5):
    x = (1 if x is None else x+1)
    # same as
    if x is None:
        x = 1
    else:
        x = x + 1
Gugu72
  • 2,052
  • 13
  • 35