2016-06-10 107 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()返回的不同事情。看看這些文檔會給你最後的提示。

相關問題