Skip to content

Eval keyword in Python

  • by

Eval is a function, not a keyword in Python. It parses the expression passed to this method and runs the python expression (code) within the program.

eval(expression, globals=None, locals=None)
x = 'print(100)'
eval(x) 

Eval keywords in Python

Simple example code where eval() function evaluates the expression x + 1 and print is used to display this value.

x = 1
print(eval('x + 1'))

print(type(eval('x + 1')))

Output:

Eval keywords in Python

Mathematical operations using the eval function

expression = 'x*(x+1)*(x+2)'
print(expression)
 
x = 3
 
result = eval(expression)
print(result)

Output:

x(x+1)(x+2)
60

Do comment if you have any doubts or suggestions on this Python function topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *