2014-10-29 98 views
1

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

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: 
+2

这是一个范围界定问题。你有一个全局变量'number'和一个变量'number',它是'checkint'的本地变量 - 这引起了混淆。一旦选中,您需要将该变量传递给该函数以使其工作。 – 2014-10-29 11:12:01

回答

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在T他外范围:

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