In this tutorial we will learn about python eval() method and it uses.
What is Python eval() Method?
The python eval() method helps execute the specified expression; it can execute the legal python statement.
The syntax of eval() method is:
Python eval() Parameters
The eval() method takes three parameters:
- expression – The simple python statement can be evaluated as a python expression.
- globals(Optional) – A dictionary containing global variable parameters.
- locals(Optional) – A dictionary containing local variable parameters.
Let’s check some examples of eval() method.
Example 1: How to use eval() method.
The output will be as follow:
In the above example, the eval() method evaluates the expression num1 + num2 then we are using the print method to print the result.
Example 2: Using eval() method with user-defined method
When we run the above program, we will get the following output.
In the above program, we create a user-defined method in which we ask users to input the value for x and y; then, we are using eval() in-built method to multiply the x and y, which is passed using expr as an argument.
eval() method with globals parameter
In eval() method, we can pass a dictionary as an argument using global parameters. It’s an optional argument that can pass a dictionary with global variables.
Global variables are all those variables that were defined in current global scope and can be accessed from anywhere in your program.
Let’s check an example of eval() with global parameters.
Example 3: eval() method with globals parameter
In the eval() method, we are passing a custom dictionary to a globals parameter as an argument. The eval() method will take only those variables which are declared as globals only.
In the above program, we declare x in the dictionary. That’s why it gives us the output, but when we are taking y, it is throwing us an error because we have not declared y in the dictionary.
Rules of eval() method.
In the eval() method, we only execute the statement if it is a string.