Python 2.7 Try And Except Valueerror
I query user input which is expected to be an int by using int(raw_input(...)) However when the user doesn't enter an integer, i.e. just hits return, I get a ValueError. def inputV
Solution 1:
A quick and dirty solution is:
parsed = Falsewhilenot parsed:
try:
x = int(raw_input('Enter the value:'))
parsed = True# we only get here if the previous line didn't throw an exceptionexcept ValueError:
print'Invalid value!'
This will keep prompting the user for input until parsed
is True
which will only happen if there was no exception.
Solution 2:
Instead of calling inputValue
recursively, you need to replace raw_input
with your own function with validation and retry. Something like this:
defuser_int(msg):
try:
returnint(raw_input(msg))
except ValueError:
return user_int("Entered value is invalid, please try again")
Solution 3:
Is something like this what you're going for?
definputValue(inputMatrix, defaultValue, playerValue):
whileTrue:
try:
rowPos = int(raw_input("Please enter the row, 0 indexed."))
colPos = int(raw_input("Please enter the column, 0 indexed."))
except ValueError:
continueif inputMatrix[rowPos][colPos] == defaultValue:
inputMatrix[rowPos][colPos] = playerValue
breakreturn inputMatrix
print inputValue([[0,0,0], [0,0,0], [0,0,0]], 0, 1)
You were right to try and handle the exception, but you don't seem to understand how functions work... Calling inputValue from within inputValue is called recursion, and it's probably not what you want here.
Post a Comment for "Python 2.7 Try And Except Valueerror"