2.8 The eval() Function (BT101CO)

The eval() function is a powerful, built-in Python tool that takes a string as an argument, parses it as a Python expression, and executes it as code. Essentially, it allows Python to run code that is generated or received as text during the program's execution.

1. Basic Syntax

The syntax for the eval() function is:

Result = eval("Expression_String")

  • Expression_String: A string containing a valid Python expression (like math or a function call).
  • Result: The value returned after the expression is evaluated.

Example:

x = 10
result = eval("x + 5")
print(result) # Output: 15

2. Using eval() with input()

A common use case for eval() is to handle user input that might be an integer, a float, or even a list, without needing multiple int() or float() conversions. It "guesses" the correct data type based on what the user types.

Example:

data = eval(input("Enter something (number/list/tuple): "))
print(type(data)) 
# If user enters 10.5, type is <class 'float'>
# If user enters [1, 2], type is <class 'list'>

4. Advanced eval() Examples

Example: Dynamic Math Formula Solver

The eval() function is perfect when you want the user to provide a full mathematical expression rather than just a single number.

# A simple "Formula Solver"
formula = input("Enter a math expression (e.g., 2 + 3 * 5): ")

# eval() handles the order of operations (BODMAS/PEMDAS) automatically
result = eval(formula)

print(f"The result of '{formula}' is: {result}")

Example: Parsing Data Structures

One of the most unique features of eval() is its ability to recognize Python's "Sequence" types (Lists, Tuples, Dictionaries) directly from a string.

# User inputs a list: [10, 20, 30]
user_list = eval(input("Enter a list of numbers: "))

print("You entered a:", type(user_list))
print("The first element is:", user_list[0])
print("The sum is:", sum(user_list))

4. The Security Risk (Important!)

While eval() is convenient, it is considered dangerous when used with untrusted user input. Because eval() executes any string as code, a malicious user could type a command to delete files or crash your system.

Warning: Never use eval() on input from a source you do not trust. For safer numerical evaluation, many developers prefer using ast.literal_eval().

Summary Table

Feature Description
Input A string representing a Python expression.
Action Parses and executes the string as live code.
Return The result of the evaluated expression.
Limitation Cannot execute statements (like loops or assignments).
Risk Can execute harmful code if input is not controlled.

eval() is often described as a "double-edged sword"—it provides incredible flexibility for dynamic problem solving, but requires careful handling to keep your program secure.

Practice Quiz