Python 2.7 try and except ValueError
我使用int(raw_input(…)查询预期为int的用户输入
但是,当用户没有输入整数时,即只点击返回,我会得到一个valueerror。
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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的部分:
1 2 3 4 5 6 7 8 9 10 11 | 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) |
快速而肮脏的解决方案是:
1 2 3 4 5 6 7 | 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!' |
这将一直提示用户输入,直到
您不需要递归地调用
1 2 3 4 5 | def user_int(msg): try: return int(raw_input(msg)) except ValueError: return user_int("Entered value is invalid, please try again") |
你要这样做吗?
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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被称为递归,这里可能不是您想要的。