我写了下面的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'
问题是intput()
对于 python2,将该值转换为数字;对于 python 3,将该值转换为字符串。
int()
非 int 字符串的 int() 返回错误,而 float 的 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()
, use eval(input())
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)