如果输入无效,Python是否返回到函数的开头?

2024-09-30 16:31:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图捕捉一个输入错误-其中唯一有效的输入是一个整数。在

如果输入了非整数,我希望它返回到func的开头并重试:

def setItorator():
 try:
  iterationCap = int(raw_input("Please enter the number of nibbles you want to make: "))
  print "You will make", iterationCap, "nibbles per file"
 except ValueError:
  print "You did not enter a valid integer, please try again"
  setItorator()
 return iterationCap 

if __name__ == "__main__":
 iterationCap = setItorator()

如果第一个输入有效,则此方法有效;如果输入无效,则返回到函数的开头,但它似乎没有将正确的valid传递回主func。我检查了sub func,它看到了正确的变量,并且类型(int)正确,但是我得到了一个错误:

^{pr2}$

如果第一个输入有效(例如“10”),只有在第一个输入无效(例如“a”后跟“10”)时,我才看到此错误


Tags: yourawmakedef错误整数intfunc
2条回答

您需要在except语句中return setItorator()。现在,您只是调用函数而忽略输出。在

试试这个。在

while True:
   try:
    i = int(raw_input("Enter value "))
    break
   except ValueError:
    print "Bad input"

print "Value is ",i

您当前的方法将递归地为每个错误调用函数,这不是一个好的实践。错误是因为在异常处理程序块中,没有定义iterationCap。在

相关问题 更多 >