New course! Every coder should learn Generative AI!
Try a free lesson+ 1
Please explain exec function in python
4 Answers
+ 8
Exec simply executes the commands you wrote in the sting as if you wrote it directly in the source code
Tip: everything in python has a __doc__ string that tells you everything you need to know regarding that thing
+ 4
As explained in other questions, eval / exec are considered bad practice because they're generally abused to do a task where they aren't needed, leading to potential security issues and generally bad programming.
thanks to Rik Wittkopp sir for explaining the dark side of this function
+ 1
No, exec and eval are not the same
eval just evaluates an expression and returns the result
So you cannot do things like eval("x=1") or eval("if a: print(b)")
(statements)
On the other hand you cannot use exec for evaluation:
exec("a+b") is possible but useless (exec always returns None)
but you can do exec("x=a+b")
0
Angelo
exec() is same as eval() ??