Built-in Functions
eval()
Evaluate a Python expression stored as text.
eval(source, globals=None, locals=None)
eval() calculates one Python expression from a string and returns its value. Only use it with trusted text, because it can run unwanted code.
Parameters
| Name | Description |
|---|---|
| source | A string or compiled code object containing one expression. |
| globals | Optional dictionary that supplies global names. |
| locals | Optional mapping that supplies local names. |
Returns
The value produced by the expression.
Try it
Run it and change it
expression = "3 * (4 + 1)" answer = eval(expression) print(answer)
Worth knowing
- Only evaluate text you trust.