3
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?

Georgy
  • 12,464
  • 7
  • 65
  • 73
jason
  • 4,721
  • 8
  • 37
  • 45
  • figured it out... somewhat. taking out the print statement makes it work. I dont understand the rule here, why it breaks with print, but Ill keep looking. – jason Apr 18 '11 at 14:28
  • 4
    "I dont understand the rule here"? Where have you seen code like this? What tutorial are you using? Where are you learning Python? This is example is severely wrong. Where did you see code like this? – S.Lott Apr 18 '11 at 15:27

6 Answers6

24

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
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
7

Assignment, including "augmented" assignment (x op= expr as shorcut for x = x op expr), is a statement, not an expression. So it doesn't result in a value. You can't print the result of something that doesn't result in anything - but that's what you're telling Python to do: "Evaluate n += p, then print the result of that."

If you want to modify n and print the new n, do that on two lines. If you just want to print the sum of n and p without modifying either, use + instead of +=.

5

You'll need to break it up onto separate lines:

n = 1
p = 4
n += p
print n
Adam Vandenberg
  • 19,991
  • 9
  • 54
  • 56
4

n += p is equal to n = n + p. This is a statement on its own and cannot be printed out. You probably meant print n + p.

EDIT:

figured it out... somewhat. taking out the print statement makes it work. I dont understand the rule here, why it breaks with print, but Ill keep looking

I would seriously suggest to get a book about Python and learn from that. You obviously (not meant as an insult, just informing you) have no idea what you are doing.

orlp
  • 112,504
  • 36
  • 218
  • 315
  • 1
    Nitpicking: It's not exactly equivalent. Objects can overload it to do in-place modification (lists do, for instance). –  Apr 18 '11 at 14:27
  • delnan: True, but offtopic for this problem. It would also confuse the asker, seeing his skill level approximated from the question. – orlp Apr 18 '11 at 14:29
1

+= is a statement. Place it on a line by itself.

Alexei Sholik
  • 7,287
  • 2
  • 31
  • 41
0

While += is generally legal Python, it is syntactically not allowed at this point, so try:

n = 1
p = 4
n += p
print n
Alexander Gessler
  • 45,603
  • 7
  • 82
  • 122