在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Python/ 在 python3 中,exec 和 eval 兩個內(nèi)置函數(shù)有什么區(qū)別?

在 python3 中,exec 和 eval 兩個內(nèi)置函數(shù)有什么區(qū)別?

內(nèi)置函數(shù)中有兩個函數(shù)的功能描述特別接近:

>>> 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.

菜鳥我傻傻的分不清,求大鳥指點兩者不同

回答
編輯回答
舊顏

eval 返回計算結(jié)果
exec 只執(zhí)行,不返回計算結(jié)果

>>> a = eval('1+1')
>>> a
2
>>> exec('a=1+2')
>>> print a
3
>>> d = exec('1+4')
SyntaxError: invalid syntax
>>> 
2017年1月11日 03:36
編輯回答
安淺陌

除了返回結(jié)果不同, eval 只接受單個表達式, exec 可以接受代碼塊, 循環(huán)控制代碼塊, 異常代碼塊, 類, 函數(shù)的定義都可以

2017年3月3日 10:59