【发布时间】:2016-01-24 11:09:14
【问题描述】:
我们被要求编写一个验证 GTIN-8 代码的程序。 验证如下:
前 7 位数字交替乘以 3,然后乘以 1
把它们加起来
从等于或大于 10 的倍数中减去该数字
得到的数字是第八位数字
这是我的代码:
def validgtin():
gtin = input("Enter the 8 digits of GTIN-8 product code: ")
valid = False
while valid == False:
if gtin.isdigit():
gtin = str(gtin)
if len(gtin) == 8:
valid = True
else:
print("That is not correct, enter 8 digits, try again: ")
gtin = input("Enter the 8 digits of GTIN-8 product code: ")
else:
print("That is not correct, type in numbers, try again: ")
gtin = input("Enter the 8 digits of GTIN-8 product code: ")
sumdigit = 3*(int(gtin[0])) + 1*(int(gtin[1])) + 3*(int(gtin[2])) + 1*(int(gtin[3])) + 3*(int(gtin[4])) + 1*(int(gtin[5])) + 3*(int(gtin[6])) #sum of the digits
gtin = str(gtin)
valid1 = False
while not valid1:
if sumdigit%10 == 0:
eightdigit = 0
else:
eightdigit = (((sumdigit + 10)//10)*10) - sumdigit
if eightdigit == (gtin[7]):
valid1 = True
print("Your GTIN-8 product code is valid.")
else:
print("Your GTIN-8 product code is not valid.")
gtin = input("Enter the 8 digits of GTIN-8 product code: ")
return
validgtin()
当我运行此代码并输入无效的 GTIN-8 代码时,它表示该代码无效并提示我输入新的 GTIN-8 代码
但是
在我输入新的有效 GTIN-8 代码后,它仍然显示它无效
与
之后发生这种情况:
Traceback (most recent call last):
File "C:\Users\Yash Dwivedi\Documents\Year 10\GCSE Computing\Assignment\Task 1 v2.py", line 29, in validgtin
if eightdigit == (gtin[7]):
IndexError: string index out of range
我不明白为什么 如有任何帮助,我将不胜感激。
【问题讨论】:
-
您可以尝试在出错之前打印 gtin
-
gtin = str(gtin)的意义何在?这在 Python 2 中是有意义的——但在这种情况下,你应该使用raw_input。另一方面,如果这个 is Python 2 则gtin.isdigit()会在用户实际上输入了仅由数字组成的内容时引发运行时错误。 -
请研究发布指南,您必须提取一个最小的发布示例,而不是您在此处引用的全部内容。这也是有原因的!
标签: python