【发布时间】: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