Search code examples
pythonpython-3.xeval

Difference between eval("input()") and eval(input()) in Python


I am trying the following function:

x = eval(input())

Giving input as 123 and type of x is also int, it works fine:

In [22]: x=eval(input("enter:"))
enter:123
In [24]: print(type(x))
<class 'int'>

But while giving input as abcd, it throws the error:

In [26]: x=eval(input("enter:"))
enter:abcd
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-26-fb0be0584c85> in <module>()
----> 1 x=eval(input("enter:"))

<string> in <module>()

NameError: name 'abcd' is not defined

Also when I changed the code to:

x=eval('input()')

It works fine:

In [27]: x=eval('input("enter:")')
enter:abcd

In [28]: print(x)
abcd

But when given input as 123, type of x is str instead of int:

In [30]: x=eval('input("enter:")')
enter:123

In [31]: print(type(x))
<class 'str'>

Solution

  • eval evaluates a piece of code. input gets a string from user input. Therefore:

    • eval(input()) evaluates whatever the user enters. If the user enters 123, the result will be a number, if they enter "foo" it will be a string, if they enter ?wrfs, it will raise an error.

    • eval("input()") evaluates the string "input()", which causes Python to execute the input function. This asks the user for a string (and nothing else), which is while 123 will be the string "123", ?wrfs will be the string "?wrfs", and "foo" will be the string '"foo"' (!).

    A third version that might make the difference apparent: eval(eval("input()")) is exactly identical to eval(input()).