What does Python's eval() do?

前端 未结 10 2082
后悔当初
后悔当初 2020-11-22 01:48

In the book that I am reading on Python, it keeps using the code eval(input(\'blah\'))

I read the documentation, and I understand it, but I still do no

10条回答
  •  执念已碎
    2020-11-22 02:25

    eval() evaluates the passed string as a Python expression and returns the result. For example, eval("1 + 1") interprets and executes the expression "1 + 1" and returns the result (2).

    One reason you might be confused is because the code you cited involves a level of indirection. The inner function call (input) gets executed first so the user sees the "blah" prompt. Let's imagine they respond with "1 + 1" (quotes added for clarity, don't type them when running your program), the input function returns that string, which is then passed to the outer function (eval) which interprets the string and returns the result (2).

    Read more about eval here.

提交回复
热议问题