-3

I am trying to execute exec('global expression_result; expression_result = %s' % "a += 2") in python.

It is giving me SyntaxError. I have already declared the variables a and expression_result.

In ipython, I have also tried i = (a += 2) this is also giving the SyntaxError

How to evaluate these kinds of expressions and get the result?

djkpA
  • 1,224
  • 2
  • 27
  • 57

5 Answers5

8

First, you should not use exec or eval. There is almost never a need for either of these functions.

Second, an assignment (e.g., a+=2) is not an expression in Python (unlike C, C++, or Java). It does not have a value and cannot be printed or further assigned. You can split your code into two assignments, as advised by other commenters:

a += 2
i = a
DYZ
  • 55,249
  • 10
  • 64
  • 93
6

You can't do it with the += sign.

But if you write it full it works.

i = a = a + 2

so drop i = a += 2 which is basically the shortcut for i = a = a + 2

Boendal
  • 2,496
  • 1
  • 23
  • 36
4

As noted by the other answers, a += 2 is not an expression in Python, so it cannot be written where an expression is expected (e.g. the right-hand-side of another assignment).

If you do want to write an assignment as an expression, this is possible since Python 3.8 using the walrus operator, but you can only use it for simple assignments, not compound assignments:

expression_result = (a := a + 2)
kaya3
  • 47,440
  • 4
  • 68
  • 97
1

I recreated your code and also, got a syntax error, any way you can use two lines?:

i = a
i += 2
not_overrated
  • 115
  • 10
1

Are you looking for this:

a+=2
i=a
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
Vaibhav Jadhav
  • 2,020
  • 1
  • 7
  • 20