Skip to content Skip to sidebar Skip to footer

What Does The Exec Keyword Do In Python?

code = compile('a = 1 + 2', '', 'exec') exec code print a 3 How it prints 3?, Can anybody tell me the exact working of it?

Solution 1:

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):
    exectest

Output:

The result of is :1.0The result of is :70.0The result of is :1.0The result of is :2.0The result of is :1.0The result of is :1.0The result of is :0.0The result of is :11.0...

Solution 2:

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?

Post a Comment for "What Does The Exec Keyword Do In Python?"