【问题标题】:Why does Python's eval(input("Enter input: ")) change input's datatype?为什么 Python eval(input("Enter input: ")) 会改变输入数据类型?
【发布时间】:2016-06-19 19:07:25
【问题描述】:

在 Python 3 中,我编写了一个简单的命令来接受来自用户的整数输入:

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

如果我跳过int() 部分并简单地使用x = input("Enter a number: "),我输入的数据类型是字符串,而不是整数。我明白了。

但是,如果我使用以下命令:

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

输入的数据类型是“int”。

为什么会这样?

【问题讨论】:

  • 可能是使用eval()时的动态类型检查?
  • eval 将输入视为用代码编写,在代码中执行 x = 3 会生成一个整数,因此 x = eval("3") 也会使 x 成为一个整数,但是让用户输入任意代码为他们的输入可能是个大问题,如果他们输入open(__file__,'w').close(),它将删除当前正在执行的文件。

标签: python eval type-conversion


【解决方案1】:

为什么会这样?

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

【讨论】:

    【解决方案2】:

    因为数字是 Python 中的有效表达式,并且它的计算结果为自身(其类型为 int)。例如,如果您输入一个不存在名称的垃圾字符串(例如,“abcdefgh”),则会引发 NameError 异常(在评估时引发异常)。

    【讨论】:

      猜你喜欢
      • 2017-03-27
      • 2020-03-08
      • 1970-01-01
      • 1970-01-01
      • 2013-08-29
      • 2016-02-19
      • 2014-03-08
      • 2019-11-22
      • 1970-01-01
      相关资源
      最近更新 更多