2011-02-17 23 views
10

me consulta de entrada de usuario que se espera que sea un entero usando int (raw_input (...))Python 2.7 try y except ValueError

Sin embargo, cuando el usuario no introduce un número entero, es decir, justo golpea retorno , Obtengo un ValueError.

def inputValue(inputMatrix, rangeRows, rangeCols, defaultValue, playerValue): 
    rowPos = int(raw_input("Please enter the row, 0 indexed.")) 
    colPos = int(raw_input("Please enter the column, 0 indexed.")) 
    while True: 
     #Test if valid row col position and position does not have default value 
     if rangeRows.count(rowPos) == 1 and rangeCols.count(colPos) == 1 and inputMatrix[rowPos][colPos] == defaultValue: 
      inputMatrix[rowPos][colPos] = playerValue 
      break 
     else: 
      print "Either the RowCol Position doesn't exist or it is already filled in." 
      rowPos = int(raw_input("Please enter the row, 0 indexed.")) 
      colPos = int(raw_input("Please enter the column, 0 indexed.")) 
    return inputMatrix 

He tratado de ser inteligente y utilizar try y except para coger el ValueError, imprimir una advertencia al usuario y luego llamar al inputValue() de nuevo. Entonces funciona cuando el usuario entra en volver a la consulta, pero se cae cuando el usuario correctamente, entonces entra en un entero

A continuación se muestra la parte del código modificado con el try y except:

def inputValue(inputMatrix, rangeRows, rangeCols, defaultValue, playerValue): 
    try: 
     rowPos = int(raw_input("Please enter the row, 0 indexed.")) 
    except ValueError: 
     print "Please enter a valid input." 
     inputValue(inputMatrix, rangeRows, rangeCols, defaultValue, playerValue) 
    try: 
     colPos = int(raw_input("Please enter the column, 0 indexed.")) 
    except ValueError: 
     print "Please enter a valid input." 
     inputValue(inputMatrix, rangeRows, rangeCols, defaultValue, playerValue) 
+2

¿Hay alguna pregunta en alguna parte? –

Respuesta

21

Una solución rápida y sucia es:

parsed = False 
while not parsed: 
    try: 
     x = int(raw_input('Enter the value:')) 
     parsed = True # we only get here if the previous line didn't throw an exception 
    except ValueError: 
     print 'Invalid value!' 

Esto evitará que preguntar al usuario para la entrada hasta parsed es True la que sólo será posible si no había ninguna excepción.

1

es algo así como esto es lo que estás buscando?

def inputValue(inputMatrix, defaultValue, playerValue): 
    while True: 
     try: 
      rowPos = int(raw_input("Please enter the row, 0 indexed.")) 
      colPos = int(raw_input("Please enter the column, 0 indexed.")) 
     except ValueError: 
      continue 
     if inputMatrix[rowPos][colPos] == defaultValue: 
      inputMatrix[rowPos][colPos] = playerValue 
      break 
    return inputMatrix 

print inputValue([[0,0,0], [0,0,0], [0,0,0]], 0, 1) 

Tenías razón para tratar de controlar la excepción, pero que no parecen entender cómo funcionan las funciones de llamadas ... inputValue desde dentro inputValue se llama recursividad, y no es probablemente lo que usted quiere aquí.

2

En lugar de llamar al inputValue recursivamente, debe reemplazar raw_input con su propia función con validación y vuelva a intentarlo. Algo como esto:

def user_int(msg): 
    try: 
    return int(raw_input(msg)) 
    except ValueError: 
    return user_int("Entered value is invalid, please try again")