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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With