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

Zii*_*Zii 6 python python-3.4

我在下面写了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'
Run Code Online (Sandbox Code Playgroud)

Cha*_* L. 4

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

int()非 int 字符串的 int() 返回错误,而 float 的 int() 则不会。

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

value=float(input())
Run Code Online (Sandbox Code Playgroud)

或者,更好(更安全)

position=int(float(value))
Run Code Online (Sandbox Code Playgroud)

编辑:最重要的是,避免使用,input因为它使用evaland 是不安全的。正如 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))
Run Code Online (Sandbox Code Playgroud)

来自 Python 文档:

PEP 3111:raw_input()已重命名为input(). 也就是说,新input() 函数从中读取一行sys.stdin并返回它,并删除尾部换行符。EOFError如果输入提前终止,则会引发该异常 。要获得 的旧行为input(),请使用eval(input()).

  • 更安全的做法是 `try:input = raw_input ; except NameError: pass`,然后在两种情况下将输入视为字符串。 (3认同)