【问题标题】:difference between python2 and python3 - int() and input()python2和python3之间的区别 - int() 和 input()
【发布时间】:2016-06-10 04:13:17
【问题描述】:

我在下面写了python代码。 而且我发现python2和python3对于1.1的输入运行结果完全不同。 为什么python2和python3之间有这样的区别? 对我来说,int(1.1) 应该是 1,然后位置是 0,1,2 范围内的有效索引 1。那你能解释一下为什么python3会有这样的结果吗?

s=[1,2,3]
while True:
  value=input()
  print('value:',value)
  try:
    position=int(value)
    print('position',position)
    print('result',s[position])
  except IndexError as err:
    print('out of index')
  except Exception as other:
    print('sth else broke',other)


$ python temp.py
1.1
('value:', 1.1)
('position', 1)
('result', 2)


$ python3 temp.py
1.1
value: 1.1
sth else broke invalid literal for int() with base 10: '1.1'

【问题讨论】:

  • 为了让它真正起作用,你可以做 position = int(float(value))
  • 您可以尝试验证值的类型吗?

标签: python python-3.4


【解决方案1】:

问题是 intput() 将值转换为 python2 的数字和 python 3 的字符串。

int() 的非 int 字符串返回错误,而 int() 的浮点数不会。

使用以下任一方法将输入值转换为浮点数:

value=float(input())

或者,更好(更安全)

position=int(float(value))

编辑:最重要的是,避免使用input,因为它使用eval 并且不安全。正如 Tadhg 所建议的,最好的解决方案是:

#At the top:
try:
    #in python 2 raw_input exists, so use that
    input = raw_input
except NameError:
    #in python 3 we hit this case and input is already raw_input
    pass

...
    try:
        #then inside your try block, convert the string input to an number(float) before going to an int
        position = int(float(value))

来自 Python 文档:

PEP 3111:raw_input() 已重命名为 input()。也就是新的input() 函数从sys.stdin 中读取一行并将其与尾随返回 换行被剥离。如果输入终止,它会引发EOFError 过早地。要获取 input() 的旧行为,请使用 eval(input())

【讨论】:

  • 更安全的方法是使用try:input = raw_input ; except NameError: pass,然后在两种情况下都将输入视为字符串。
【解决方案2】:

请查看 Python 3 发行说明。特别是,input() 函数(被认为是危险的)已被删除。取而代之的是,更安全的 raw_input() 函数被重命名为 input()

为了编写两个版本的代码,只依赖raw_input()。将以下内容添加到文件顶部:

try:
    # replace unsafe input() function
    input = raw_input
except NameError:
    # raw_input doesn't exist, the code is probably
    # running on Python 3 where input() is safe
    pass

顺便说一句:您的示例代码不是最小的。如果您进一步减少代码,您会发现在一种情况下int()float 上运行,而在另一种情况下在str 上运行,这将带给您input() 返回的不同内容。看看文档会给你最后的提示。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    相关资源
    最近更新 更多