2014-10-29 73 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