pythonsyntax-erroraugmented-assignment

"+=" causing SyntaxError in Python


n = 1
p = 4
print n += p

gives me:

File "p7.py", line 17

print n += p

SyntaxError: invalid syntax

How can this problem be fixed?


Solution

  • n += p is a statement in Python, not an expression that returns a value you could print. This is different from a couple of other languages, for example Ruby, where everything is an expression.

    You need to do

    n += p
    print n