我写下了python代码。 我发现python2和python3对于1.1的输入有完全不同的运行结果。 为什么python2和python3有这种区别? 对于我来说,int(1.1)应该是1,那么位置是在范围0,1,2内的有效索引1。那么你能解释为什么python3有这样的结果吗?python2和python3的区别 - int()和input()
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)) –
你可以尝试验证值的类型吗? –