Back to Python
2026-03-255 min read

Python eval()

Learn Python eval() step by step with clear examples and exercises.

Why This Matters

In this full guide, we delve deep into the eval() function in Python. Understanding how to dynamically execute Python expressions using eval() can help you tackle complex problems, debug tricky situations, and even prepare for interviews and exams.

Why This Matters

The eval() function is a powerful tool that allows you to evaluate Python expressions, call functions, or even create new variables on the fly. By mastering its use, you can write more flexible, adaptable code that can handle a wider range of inputs and scenarios.

Prerequisites

To fully grasp the concepts presented in this guide, it is essential that you have a good understanding of Python basics such as variables, data types, control structures like if-else statements and loops, and functions.

Core Concept

What is eval()?

The eval() function takes a string containing Python code as an argument and executes it within the current scope. This means that you can use eval() to evaluate expressions, call functions, or even create new variables on the fly.

Define a simple expression

expression = "2 + 3"

Evaluate the expression using eval()

result = eval(expression)

print(result) # Output: 5


In this example, we define a string containing an arithmetic expression. By passing this string to `eval()`, we can evaluate the expression and print the result.

### Using eval() with functions

You can also use `eval()` to call functions dynamically by passing their names as strings. However, be aware that using `eval()` in this way can lead to security risks if you are not careful (more on this later).

Define a function

def add_numbers(a, b):

return a + b

Get the name of the function as a string

function_name = "add_numbers"

Use eval() to call the function with two arguments

result = eval(f"{function_name}(4, 5)")

print(result) # Output: 9


In this example, we define a function `add_numbers()`. We then use `eval()` to call the function using its name as a string and pass two arguments.

### eval() and variables

Besides executing expressions and calling functions, you can also use `eval()` to create or manipulate variables dynamically by passing strings containing variable names and values.

Use eval() to create a new variable

variable_name = "my_var"

variable_value = 10

eval(f"{variable_name} = {variable_value}")

Access the newly created variable

print(my_var) # Output: 10


In this example, we create a new variable `my_var` using `eval()`. We then access the variable and print its value.

### Caution: Security Risks with eval()

While `eval()` can be incredibly useful, it is essential to understand that using it comes with security risks. Since `eval()` executes arbitrary Python code, if you pass a string containing malicious code as an argument, the code will be executed within your program's context. To mitigate this risk, always ensure that the strings passed to `eval()` come from trusted sources or are properly sanitized before use.

Worked Example

Let's put everything we've learned into practice by building a simple calculator using eval().

def calculate(expression):
result = eval(expression)
return result

Test the calculator with some examples

print("Addition: ", calculate("2 + 3"))

print("Subtraction: ", calculate("5 - 2"))

print("Multiplication: ", calculate("7 * 4"))

print("Division: ", calculate("10 / 2"))


In this example, we define a function `calculate()` that takes an expression as an argument and returns the result of evaluating the expression using `eval()`. We then test our calculator with various arithmetic operations.

Common Mistakes

  1. Forgetting to wrap expressions in quotes: When passing expressions containing operators or variables as strings, make sure to enclose them in quotes (e.g., "2 + 3" instead of 2 + 3).
  1. Not properly sanitizing user input: If you are using eval() with user-provided input, always ensure that the input is properly sanitized to prevent security risks.
  1. Using eval() for simple calculations: In many cases, it's more efficient and safer to use built-in Python functions like +, -, *, and / for simple arithmetic operations instead of using eval().
  1. Not handling exceptions: When using eval(), be sure to handle potential exceptions that may occur during the execution of the passed code, such as NameError or SyntaxError.

Practice Questions

  1. Write a function that takes two numbers as arguments and returns their sum using eval().
  2. Create a program that prompts the user for an expression containing variables, evaluates the expression using eval(), and prints the result. Make sure to sanitize the user input.
  3. Use eval() to create a new list containing the numbers 1 through 5.
  4. Write a function that takes a string representing a mathematical equation and returns its solution using eval(). The equation should include variables, operators, and parentheses.
  5. Modify the calculator from the worked example to handle user input and exceptions.

FAQ

Q: Why is it dangerous to use eval() with user-provided input?

A: Using eval() with user-provided input can be risky because the user's input will be executed within your program's context, potentially allowing them to run arbitrary code or access sensitive information. To mitigate this risk, always ensure that the input is properly sanitized before passing it to eval().

Q: Can I use eval() with lists and other complex data structures?

A: Yes! You can use eval() with lists, dictionaries, and other complex data structures by passing strings representing these structures as arguments. However, be aware that using eval() in this way can make your code more difficult to read and maintain, so it's generally best to avoid it if possible.

Q: Is there a safer alternative to eval() for simple calculations?

A: Yes! For simple arithmetic operations like addition, subtraction, multiplication, and division, it is safer and more efficient to use the built-in Python operators instead of eval(). When dealing with complex expressions that involve variables or functions, however, using eval() may be necessary.

Q: How can I handle exceptions when using eval()?

A: To handle exceptions when using eval(), you can wrap the call to eval() in a try-except block. This allows you to catch and handle any exceptions that occur during the execution of the passed code. Here's an example:

try:
result = eval(expression)
except NameError as e:
print("NameError:", e)
except SyntaxError as e:
print("SyntaxError:", e)
except Exception as e:
print("Unexpected error:", e)

In this example, we catch and handle NameError, SyntaxError, and any other exceptions that may occur during the execution of the passed code.

Python eval() | Python | XQA Learn