The exec and eval Statements


A Byte of Python 

Go to the Table of Contents. Visit the Gifcom web site.

The exec statement is used to execute Python statements which are stored in a string or file. For example, we can generate a string containing Python code at runtime and then execute these statements using the exec statement. A simple example is shown below.

		
>>> exec 'print "Hello World"'
Hello World
		
		

The eval statement is used to evaluate valid Python expressions which are stored in a string. A simple example is shown below.

		
>>> eval('2*3')
6