【发布时间】:2014-12-25 01:34:38
【问题描述】:
我在 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:
【问题讨论】:
-
这是一个范围界定问题。您有一个全局变量
number,还有一个变量number是checkint的局部变量——这会引起混淆。检查后,您需要将变量传递出函数以使其工作。
标签: python validation input while-loop traceback