在 python3 中,exec 和 eval 两个内置函数有什么区别?

内置函数中有两个函数的功能描述特别接近:

>>> help(eval)
Help on built-in function eval in module builtins:

eval(source, globals=None, locals=None, /)
    Evaluate the given source in the context of globals and locals.

    The source may be a string representing a Python expression
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.
>>> help(exec)
Help on built-in function exec in module builtins:

exec(source, globals=None, locals=None, /)
    Execute the given source in the context of globals and locals.

    The source may be a string representing one or more Python statements
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.

菜鸟我傻傻的分不清,求大鸟指点两者不同

阅读 3.1k
2 个回答

eval 返回计算结果
exec 只执行,不返回计算结果

>>> a = eval('1+1')
>>> a
2
>>> exec('a=1+2')
>>> print a
3
>>> d = exec('1+4')
SyntaxError: invalid syntax
>>> 
新手上路,请多包涵

除了返回结果不同, eval 只接受单个表达式, exec 可以接受代码块, 循环控制代码块, 异常代码块, 类, 函数的定义都可以

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题