繁体   English   中英

python2和python3之间的区别 - int()和input()

[英]difference between python2 and python3 - int() and input()

我在下面写了python代码。 我发现python2和python3对于1.1的输入有完全不同的运行结果。 为什么python2和python3之间有这样的区别? 对我来说,int(1.1)应该是1,那么position是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'

问题是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())

请查看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()返回的不同内容。 看一下这些文档会给你最后的提示。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM