gpt4 book ai didi

错误处理后 while 循环中的 Python 回溯错误

转载 作者:行者123 更新时间:2023-12-01 04:59:20 24 4
gpt4 key购买 nike

我用 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:

最佳答案

这是一个说明问题的最小示例:

>>> def change(x):
x = 2
print x

>>> x = 1
>>> change(x)
2 # x inside change
>>> x
1 # is not the same as x outside

您需要修复该函数以返回某些内容,并将其分配给外部作用域中的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

关于错误处理后 while 循环中的 Python 回溯错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26628798/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com