Python 2.7 try and except ValueError

前端 未结 3 1358
抹茶落季
抹茶落季 2021-02-07 07:33

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

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-07 07:41

    Is something like this what you're going for?

    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)
    

    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.

提交回复
热议问题