开发者

"+=" causing SyntaxError in Python

开发者 https://www.devze.com 2023-02-26 23:16 出处:网络
n = 1 p = 4 print n += p gives me: 开发者_运维百科File \"p7.py\", line 17 print n += p SyntaxError: invalid syntax
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?


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


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 +=.


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

n = 1
p = 4
n += p
print n


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.


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


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

n = 1
p = 4
n += p
print n
0

精彩评论

暂无评论...
验证码 换一张
取 消