Python 如何阻止GTIN程序重新启动自身?
输入错误的输入后,通过输出“VALID”或“INVALID”检查序列的有效性,直到此时为止。但在此之后,由于某种原因,程序再次重新启动。如果输入都是整数,并且通过了验证检查,则程序输出“有效”或“无效”,并在那里结束,但当输入错误时,程序会自行重新启动Python 如何阻止GTIN程序重新启动自身?,python,Python,输入错误的输入后,通过输出“VALID”或“INVALID”检查序列的有效性,直到此时为止。但在此之后,由于某种原因,程序再次重新启动。如果输入都是整数,并且通过了验证检查,则程序输出“有效”或“无效”,并在那里结束,但当输入错误时,程序会自行重新启动 def first_stage(): digcode = [] #stores the GTIN sequence
def first_stage():
digcode = [] #stores the GTIN sequence
the_list = [3,1,3,1,3,1,3]
for counter in range(7):
digit = input("digit:")
if len(digit) > 1 or len(digit) == 0 or digit[0] == "-":
print("please enter one positive integer")
first_stage() #restarts program to acquire all the numbers
try:
digit = int(digit)
except:
print("please enter an integer")
first_stage()
calculation = digit*(the_list[counter])
digcode.append(calculation)
the_sum = sum(digcode)
check_digit = 10-(the_sum%10) #modular division to calculate the eighth digit
if check_digit == 10:
digcode.append(0)
second_stage(digcode)
else:
digcode.append(check_digit)
second_stage(digcode)
def second_stage(digcode):
the_list3 = []
the_list2 = [3,1,3,1,3,1,3,1]
for counter in range(8):
calculation2 = digcode[counter]*the_list2[counter]
the_list3.append(calculation2)
the_sum2 = sum(the_list3)
validate = the_sum2/10
if validate == int(validate):
print("VALID")
else:
print("INVALID")
first_stage()
即使在收到输入后,它仍会继续重新启动。它重新启动的次数不同,因此可能取决于我的输入。在某个时刻,它确实停止重新启动,并输出一条关于TypeError的长错误消息。请在您的问题中提供回溯。您的代码中确实有几个递归调用。有关验证不使用递归的用户输入的更好方法,请参阅。
digit:1
digit:2
digit:a
please enter an integer
digit:1
digit:2
digit:3
digit:4
digit:5
digit:6
digit:7
INVALID
digit: