Python eval() Built in Function

The eval() function in Python is used to evaluate a string or an object that contains a valid Python expression, which is a code that returns a value. The eval() function takes a string or an object that contains a valid Python expression and evaluates it as if it was written in a file. You can also pass a dictionary of global and local variables to the eval() function to modify the evaluation environment. Here are some examples of using eval() in Python:

Evaluate a mathematical expression stored as a string:

result = eval('3 + 4 * 2')

print(result)

Output: 11

In this example, eval('3 + 4 * 2') evaluates the mathematical expression '3 + 4 * 2' and returns the result (11). Note that eval() can be dangerous if used improperly, as it allows arbitrary code execution. You should only use eval() with trusted input.

Evaluate a Python expression that references variables in your program:

x = 5
y = 10


result = eval('x * y')

print(result)

Output: 50

In this example, eval('x * y') evaluates the Python expression 'x * y' and returns the result (50). Note that the eval() function has access to the variables in your program, so you can use it to evaluate expressions that reference those variables.

Use eval() to execute arbitrary code entered by the user:

code = input("Enter some Python code: ")

result = eval(code)


print(result)

In this example, we prompt the user to enter some Python code, and then use eval() to execute that code and return the result. This allows the user to enter arbitrary Python code and see the result, which can be useful for interactive exploration and experimentation. However, as mentioned earlier, this is potentially dangerous if the input is not trusted.

Some more examples:

# Evaluate a simple expression
x = 10
y = 20
exp = "x + y"
result = eval(exp)
print(result)
# Output: 30


# Evaluate a user input
exp = input("Enter some Python expression: ")
result = eval(exp)
print(result)

# For example, if you enter x**2 + y**2, it will print 500


# Evaluate a code with global and local variables
global_var = {"x": 5}
local_var = {"y": 10}
exp = "x * y"
result = eval(exp, global_var, local_var)
print(result)
# Output: 50

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions