【问题标题】:Python Traceback error in while loop after error handling错误处理后while循环中的Python Traceback错误
【发布时间】: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,还有一个变量numbercheckint 的局部变量——这会引起混淆。检查后,您需要将变量传递出函数以使其工作。

标签: python validation input while-loop traceback


【解决方案1】:

以下是说明问题的最小示例:

>>> 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

【讨论】:

    猜你喜欢
    • 2015-02-07
    • 2013-05-18
    • 2014-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多