What does Python's eval() do?

前端 未结 10 2085
后悔当初
后悔当初 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:21

    I'm late to answer this question but, no one seems to give clear answer to the question.

    If an user enters a numeric value, input() will return a string.

    >>> input('Enter a number: ')
    Enter a number: 3
    >>> '3'
    >>> input('Enter a number: ')
    Enter a number: 1+1
    '1+1'
    

    So, eval() will evaluate returned value (or expression) which is a string and return integer/float.

    >>> eval(input('Enter a number: '))
    Enter a number: 1+1
    2
    >>> 
    >>> eval(input('Enter a number: '))
    Enter a number: 3.14
    3.14
    

    Of cource this is a bad practice. int() or float() should be used instead of eval() in this case.

    >>> float(input('Enter a number: '))
    Enter a number: 3.14
    3.14
    

提交回复
热议问题