2016-06-10 17 views
5

Ho scritto sotto il codice Python. E ho scoperto che python2 e python3 hanno totalmente differenza nel risultato in esecuzione per l'input di 1.1. Perché c'è una tale differenza tra python2 e python3? Per me, int (1.1) dovrebbe essere 1, quindi la posizione è indice valido 1 entro l'intervallo 0,1,2. Quindi, per favore, puoi spiegare perché python3 ha tale risultato?differenza tra python2 e python3 - int() e 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

Per far sì che funzioni davvero, puoi fare position = int (float (valore)) –

+1

Puoi provare a verificare il tipo di valore? –

risposta

4

Il problema è intput() converte il valore di un numero di python2 e una stringa per pitone 3.

int() di una stringa non int restituisce un errore, mentre int() di un galleggiante no.

Convertire il valore di ingresso ad un galleggiante utilizzando:

value=float(input()) 

o, meglio (più sicuro) ancora

position=int(float(value)) 

EDIT: E soprattutto, evitare di utilizzare input in quanto utilizza un eval ed è pericoloso Come suggerito Tadhg, la soluzione migliore è:

#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)) 

dalla documentazione 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

sarebbe ancora più sicuro fare 'try: input = raw_input; tranne NameError: pass' e quindi considerare l'input come una stringa in entrambi gli scenari. –

1

Si prega di controllare le note di rilascio di Python 3. In particolare, la funzione input() (che è considerata pericolosa) è stata rimossa. Al suo posto, la funzione più sicura raw_input() è stata rinominata in input().

Per scrivere codice per entrambe le versioni, fare affidamento solo su raw_input(). Aggiungere il seguente all'inizio del file:

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 

BTW: Il codice di esempio non è minimo. Se avessi ulteriormente ridotto il codice, avresti trovato che in un caso int() opera su un float e nell'altro su un str che poi ti avrebbe portato alle diverse cose che restituisce input(). Uno sguardo ai documenti avrebbe quindi dato il suggerimento finale.

Problemi correlati