python eval和exec的区别

The eval function is used to evaluate a single expression and return its value. For example:

x = 1
y = 2
z = eval("x + y")
print(z)  # Output: 3

In this example, the eval function evaluates the expression “x + y”, which adds the values of x and y together, and returns the result (3).

On the other hand, the exec function is used to execute a block of code. It does not return a value, but instead modifies the current environment. For example:

x = 1
y = 2
exec("z = x + y")
print(z)  # Output: 3

In this example, the exec function executes the code “z = x + y”, which assigns the value of x + y to the variable z. Since exec modifies the current environment, the value of z is accessible outside of the exec block.

In summary, eval is used to evaluate a single expression and return its value, while exec is used to execute a block of code and modify the current environment.

推荐大家一个在国内也能访问的智能代码查询工具,Cursor,使用了类似ChatGPT的技术。
Cursor传送门

你可能感兴趣的:(Python,python)