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

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?

 

回答1

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

 

posted @ 2022-09-17 17:26  ChuckLu  阅读(16)  评论(0)    收藏  举报