为什么 Python 的 eval(input("Enter input: ")) 会改变输入的数据类型?
Why does Python's eval(input("Enter input: ")) change input's datatype?
在Python3中,我写了一个简单的命令来接受用户的整数输入:
x = int(input("Enter a number: "))
如果我跳过 int()
部分而只使用 x = input("Enter a number: ")
,我输入的数据类型是字符串,而不是整数。我明白了。
但是,如果我使用以下命令:
x = eval(input("Enter a number: "))
输入的数据类型是'int'。
为什么会这样?
Why does this happen?
x = eval(input("Enter a number: "))
与 x = eval('input("Enter a number: ")')
不同
前者先调用input(...)
,得到一个字符串,例如'5'
然后计算它,这就是为什么你得到一个 int
,以这种方式:
>>> eval('5') # the str '5' is e.g. the value it gets after calling input(...)
5 # You get an int
而后者(更符合您的预期)计算表达式 'input("Enter a number: ")'
>>> x = eval('input("Enter a number: ")')
Enter a number: 5
>>> x
'5' # Here you get a str
因为数字在 Python 中是有效的表达式,并且它的计算结果为自身(并且其类型为 int)。例如,如果您输入一个不存在的名称的垃圾字符串(例如,'abcdefgh'),将引发 NameError 异常(评估时引发异常)。
在Python3中,我写了一个简单的命令来接受用户的整数输入:
x = int(input("Enter a number: "))
如果我跳过 int()
部分而只使用 x = input("Enter a number: ")
,我输入的数据类型是字符串,而不是整数。我明白了。
但是,如果我使用以下命令:
x = eval(input("Enter a number: "))
输入的数据类型是'int'。
为什么会这样?
Why does this happen?
x = eval(input("Enter a number: "))
与 x = eval('input("Enter a number: ")')
前者先调用input(...)
,得到一个字符串,例如'5'
然后计算它,这就是为什么你得到一个 int
,以这种方式:
>>> eval('5') # the str '5' is e.g. the value it gets after calling input(...)
5 # You get an int
而后者(更符合您的预期)计算表达式 'input("Enter a number: ")'
>>> x = eval('input("Enter a number: ")')
Enter a number: 5
>>> x
'5' # Here you get a str
因为数字在 Python 中是有效的表达式,并且它的计算结果为自身(并且其类型为 int)。例如,如果您输入一个不存在的名称的垃圾字符串(例如,'abcdefgh'),将引发 NameError 异常(评估时引发异常)。