2011-02-17 81 views
10

我查询其预计使用INT(的raw_input(...))将int用户输入Python 2.7版尝试,除了ValueError异常

然而,当用户不输入一个整数,即只打回,我得到一个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 

我试图将智能和使用尝试除非赶上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) 
+2

在那里有问题吗? – 2011-02-17 05:29:13

回答

21

一个快速和肮脏的解决方案是:

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

是一样的东西:然后当用户输入返回查询,但落在当用户正确,然后进入一个整数

下面了是修订后的代码与尝试,除了部分工程这是你要做什么?

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的调用被称为递归,这可能不是你想要的这里。

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")