In Python, the eval() function is an underlying Python function that evaluates a string as a Python expression. It takes a single parameter, which is a string that addresses a Python expression. The eval() function then evaluates this expression and returns the outcome. The python eval() function parses the expression passed to it and runs python expression(code) within the program.
The eval() function is in many cases used in Python to execute dynamically produced code. For instance, on the off chance that you have a string that contains a numerical expression, you can use the eval() function to evaluate that expression and return the outcome.
It has the following syntax:
It returns the result evaluated from the expression.
Here, we are going to discuss several examples that demonstrate the working of eval() Function.
In this example, the eval() function is used to evaluate a string expression that includes variables and returns the computed result.
Output:
40
Explanation:
In this example, we have defined two variables x and y and introduced them with the values 15 and 25, separately. After that, we call the eval() function with the string 'x + y' as the expression. The eval() function evaluates this expression as the sum of the values of x and y, which is 40. At last, we print the outcome using the print() function.
In this example, the eval() function is used with globals() and locals() to evaluate an expression within a specific scope, allowing access to both global and local variables.
Output:
20
Explanation:
In this example, we have defined two variables x and y, and a string expr that contains a Python expression. After that, we call the eval() function with the globals() and locals() functions as contentions, which address the global and local namespaces, separately. The eval() function evaluates the expression 'x + y' utilizing the globals() and locals() namespaces and returns the outcome, which is 20.
In this example, the eval() function is used with a custom local dictionary to provide additional variables, allowing the expression to be evaluated with values not directly defined in the code.
Output:
100
Explanation:
In this example, we have taken two variables x and y, and a string expression x + y + z. Since z is not defined directly, we pass its value using a dictionary. The eval() function then calculates the result using these values and returns 100.
We request you to subscribe our newsletter for upcoming updates.