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)
¿Hay alguna pregunta en alguna parte? –