错误处理后while循环中的Python Traceback错误

时间:2014-10-29 11:09:20

标签: python validation input while-loop traceback

我在Python 3.4.1中创建了一个程序; 要求整数, 验证它是一个整数, 如果不是整数,则抛出错误消息并要求重新输入数字, 验证号码后,将其添加到列表中, 如果输入-1则结束。

mylist = []

def checkint(number):
    try:
        number = int(number)
    except:
        print ("Input not accepted, please only enter whole numbers.")
        number = input("Enter a whole number. Input -1 to end: ")
        checkint(number)


number = input("Enter a whole number. Input -1 to end: ")
checkint(number)

while int(number) != -1:

    mylist.append(number)
    number = input("Enter a whole number. Input -1 to end: ")
    checkint(number)   

这一切都很好,除了一个场景。如果输入非整数,例如p(提供错误消息)后跟-1来结束程序,我收到此消息:

Traceback (most recent call last):
  File "C:/Users/************/Documents/python/ws3q4.py", line 15, in <module>
    while int(number) != -1:
ValueError: invalid literal for int() with base 10: 'p'

我不明白为什么会发生这种情况,因为p的输入应该永远不会达到

while int(number) != -1:

1 个答案:

答案 0 :(得分:2)

这是一个说明问题的最小例子:

>>> def change(x):
        x = 2
        print x

>>> x = 1
>>> change(x)
2 # x inside change
>>> x
1 # is not the same as x outside

您需要将该功能修复为return某事,并将其分配给外部范围内的number

def checkint(number):
    try:
        return int(number) # return in base case
    except:
        print ("Input not accepted, please only enter whole numbers.")
        number = input("Enter a whole number. Input -1 to end: ")
        return checkint(number) # and recursive case

number = input("Enter a whole number. Input -1 to end: ")
number = checkint(number) # assign result back to number

此外,最好是迭代而不是递归地执行此操作 - 请参阅例如Asking the user for input until they give a valid response