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