What is the difference between the two built-in functions exec and eval in python3?

there are two built-in functions that have very similar functional descriptions:

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

I am so silly that I can"t tell the difference between a rookie and a rookie. I ask the big bird for advice on the difference between the two

Mar.01,2021

eval returns the calculation result
exec only executes, but does not return the calculation result

>>> a = eval('1+1')
>>> a
2
>>> exec('a=1+2')
>>> print a
3
>>> d = exec('1+4')
SyntaxError: invalid syntax
>>> 

in addition to returning different results, eval only accepts a single expression, and exec can accept code blocks, loop control code blocks, exception code blocks, classes, and function definitions

.
Menu