我通过使用int(raw_input(...))查询预期为int的用户输入
但是,当用户没有输入整数时,即只是命中返回时,我得到一个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和除了捕获ValueError,向用户输出警告然后再次调用inputValue() . 然后它在用户输入返回查询时起作用,但在用户正确输入整数时倒下
以下是修改后的代码的一部分,其中包括:
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 回答
快速而肮脏的解决方案是:
这将继续提示用户输入,直到
parsed
为True
,这只有在没有异常的情况下才会发生 .您需要使用自己的函数将
raw_input
替换为验证并重试,而不是递归调用inputValue
. 像这样的东西:这是你想要的东西吗?
你是正确的尝试处理异常,但你似乎不理解函数如何工作...从inputValue中调用inputValue称为递归,它可能不是你想要的 .