简体   繁体   中英

How to use eval inside exec in Python 2

After I've learned about these 2 functions. Ive been wondering how to use the eval() inside the exec() function. I ask this didactically.

I tried this and other variations in the console but it was unsuccessful:

exec "eval("1+1")"

You are using double-quotes to both surround the expression being exec d and its argument, which confuses the parser; you can either escape the inner ones or use single-quotes for them.

Legal syntax would be exec("eval('1+1')") but that is pretty pointless, exec is for statements.

In [25]: exec("eval('1+1')")

In [26]: exec("print(1+1)")
2
In [27]: exec("a = eval('1+1')")
In [28]: a
Out[28]: 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM