2016-06-10 109 views
5

我写下了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' 
+0

为了使它真的有效,你可以做position = int(float(value)) –

+1

你可以尝试验证值的类型吗? –

回答

4

问题是intput()的值转换为用于python2的数目和用于蟒字符串3.

非INT串的int()返回一个错误,而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() 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()) .

+3

更安全的是做'try:input = raw_input;除了NameError:pass'外,在两种情况下都将输入视为字符串。 –

1

请检查Python 3的发布说明。特别是,input()函数(被认为是危险的)已被删除。取而代之,更安全的raw_input()函数被重命名为input()

为了编写两个版本的代码,只能依靠raw_input()。将以下内容添加到文件顶部:

try: 
    # replace unsafe input() function 
    input = raw_input 
except NameError: 
    # raw_input doesn't exist, the code is probably 
    # running on Python 3 where input() is safe 
    pass 

顺便说一句:您的示例代码不是最小的。如果您进一步减少了代码,您会发现在一种情况下,int()float上运行,在另一个情况下在str上运行,然后它会带您返回input()返回的不同事情。看看这些文档会给你最后的提示。

相关问题