首页 文章

Python 2.7尝试和ValueError除外

提问于
浏览
13

我通过使用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 回答

  • 27

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

    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 ,这只有在没有异常的情况下才会发生 .

  • 2

    您需要使用自己的函数将 raw_input 替换为验证并重试,而不是递归调用 inputValue . 像这样的东西:

    def user_int(msg):
      try:
        return int(raw_input(msg))
      except ValueError:
        return user_int("Entered value is invalid, please try again")
    
  • 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称为递归,它可能不是你想要的 .

相关问题