-3
code = compile('a = 1 + 2', '<string>', 'exec')
exec code
print a
3

How it prints 3?, Can anybody tell me the exact working of it?

Harshit Agarwal
  • 878
  • 3
  • 10
  • 19

2 Answers2

2

So the exec statement can be used to execute code stored in strings. This allows you to store code in strings. Naturally all manipulations that are valid on strings can be done. This is demonstrated below:

Note: exec is a statement in python 2.7x and a function on 3.x

import random
statement = 'print "%s"%(random.random());
exec statement

Output:

>>> runfile(...)
0.215359778598
>>> runfile(...)
0.702406617438
>>> runfile(...)
0.455131491306

See also: Difference between eval, exec and compile

It can come in pretty handy while testing complex math functions. For instance:

def someMath(n,m,r): return (n**m)//r

import random
test = 'print "The result of is: ", someMath(random.random(),random.random(),random.random())'
for i in range(20):
    exec test

Output:

The result of is : 1.0
The result of is :  70.0
The result of is :  1.0
The result of is :  2.0
The result of is :  1.0
The result of is :  1.0
The result of is :  0.0
The result of is :  11.0
...
Community
  • 1
  • 1
shaunakde
  • 3,009
  • 3
  • 24
  • 39
1

Exec statement is used to execute Python code contained in string. Then a = 1 + 2 = 3.

More info here: What's the difference between eval, exec, and compile in Python?

Community
  • 1
  • 1