python2和python3的区别——int()和input() [英] difference between python2 and python3 - int() and input()

查看:47
本文介绍了python2和python3的区别——int()和input()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I wrote below python code. And I found that python2 and python3 has totally difference running result for input of 1.1. Why is there such difference between python2 and python3? For me, int(1.1) should be 1, then position is valid index 1 within range 0,1,2. So can you please explain why python3 has such result?

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 的字符串.

The issue is intput() converts the value to an number for python2 and a string for python 3.

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

int() of a non int string returns an error, while int() of a float does not.

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

Convert the input value to a float using either:

value=float(input())

或者,更好(更安全)

position=int(float(value))

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

And best of all, avoid using input since it uses an eval and is unsafe. As Tadhg suggested, the best solution is:

#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 文档:

From the Python Docs:

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

PEP 3111: raw_input() was renamed to input(). That is, the new input() function reads a line from sys.stdin and returns it with the trailing newline stripped. It raises EOFError if the input is terminated prematurely. To get the old behavior of input(), use eval(input()).

这篇关于python2和python3的区别——int()和input()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆