Have you ever encountered an error using the exec or eval functions? In my case, I got caught quite often. In this article, I will explain the exec and eval functions with brief explanations and examples.
The exec function is a function that executes a statement. For example
sample.py
exec("x=5")
print(x)
#Execution result: 5
In this example, the exec function executes the statement of assigning 5 to x.
sample.py
x = exec("5+5")
print(x)
#Execution result: None
Since the exec function is a function that executes a statement, passing an expression does not return the execution result.
The eval function is a function that calculates an expression and returns the result. For example
sample.py
x = eval("5+5")
print(x)
#Execution result: 10
The exec function did not return the calculation result when I passed the expression, but the eval function did.
sample.py
eval("x=5")
print(x)
#SyntaxError: invalid syntax in line 1
Since the eval function is a function that calculates an expression, passing a statement will cause a SyntaxError.
Have you read this article and found out about the differences between the exec and eval functions? If you have any comments, please write them in the comments.
Recommended Posts