Python 2.7尝试和ValueError除外

时间:2011-02-17 05:27:20

标签: python exception-handling

我通过使用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()。然后它在用户输入返回查询时起作用,但在用户正确输入整数

时倒下

下面是使用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 个答案:

答案 0 :(得分:28)

快速而肮脏的解决方案是:

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!'

这会一直提示用户输入parsedTrue,只有在没有例外时才会发生。

答案 1 :(得分:2)

不是递归调用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")

答案 2 :(得分: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)

您尝试处理异常是正确的,但您似乎并不理解函数是如何工作的......从inputValue中调用inputValue称为递归,它可能不是您想要的。