Python 2.7 的 try 和 except ValueError
我用 int(raw_input(...)) 来获取用户输入,期望用户输入一个整数。
但是当用户没有输入整数,比如直接按回车键时,我就会遇到一个叫 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
我想得比较聪明,使用了 try 和 except 来捕捉这个 ValueError,给用户打印一个警告,然后再调用 inputValue() 让用户重新输入。这样当用户按回车时就能正常工作,但如果用户之后正确输入了一个整数,就又出错了。
下面是修改后代码的一部分,包含了 try 和 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)
3 个回答
1
你想要的东西是这样的吧?
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)
你处理异常的做法是对的,但你似乎不太明白函数是怎么工作的……在函数内部再调用自己,这种情况叫做递归,可能不是你想要的结果。
3
与其递归地调用 inputValue
,不如把 raw_input
替换成你自己写的一个函数,这个函数要包含验证和重试的功能。可以像这样做:
def user_int(msg):
try:
return int(raw_input(msg))
except ValueError:
return user_int("Entered value is invalid, please try again")
37
一个简单粗暴的解决办法是:
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!'
这个方法会一直让用户输入内容,直到parsed
变成True
。只有在没有发生错误的情况下,parsed
才会变成True
。