Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Python's eval(input("Enter input: ")) change input's datatype?

In Python 3, I write a simple command to accept an integer input from the user thus:

x = int(input("Enter a number: "))

If I skip the int() part and simply use x = input("Enter a number: "), my input's datatype is a string, not an integer. I understand that.

However, if I use the following command:

x = eval(input("Enter a number: "))

the input's datatype is 'int'.

Why does this happen?

like image 425
lebowski Avatar asked Jun 19 '16 19:06

lebowski


1 Answers

Why does this happen?

x = eval(input("Enter a number: ")) is not the same thing as x = eval('input("Enter a number: ")')

The former first calls input(...), gets a string, e.g. '5' then evaluates it, that's why you get an int, in this manner:

>>> eval('5') # the str '5' is e.g. the value it gets after calling input(...)
5 # You get an int

While the latter (more aligned with what you were expecting), evaluates the expression 'input("Enter a number: ")'

>>> x = eval('input("Enter a number: ")')
Enter a number: 5
>>> x 
'5' # Here you get a str
like image 99
bakkal Avatar answered Nov 14 '22 20:11

bakkal