[英]Why am I getting this Error “IndexError: string index out of range”
我们被要求编写一个验证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
我不明白为什么我会感谢您的帮助。
我建议创建一个“ is_valid_gtin”函数,该函数仅在没有I / O的情况下检查GTIN是否有效。 然后一个简单的“ main()”来检查代码:
def is_valid_gtin(gtin):
if len(gtin) != 8 or not gtin.isdigit():
return False
sum = 0
for i in list(gtin)[0:6:2]:
sum += 3*int(i)
for i in list(gtin)[1:6:2]:
sum += int(i)
checksum = (10 - sum % 10) % 10
return checksum == int(gtin[7])
def main():
while (True):
gtin = input("Enter the 8 digits of GTIN-8 product code: ")
if is_valid_gtin(gtin):
print("Your GTIN-8 product code is valid.")
break
else:
print("That is not correct, try again.")
if __name__ == '__main__':
main()
这是我的快速实施。 遗憾的是,我没有任何测试数据来检查其是否正确!
def _round_up_ten(number):
if number % 10 == 0:
return number
return 10 * (1 + (number / 10))
def validate_gtin(gtin):
if not gtin.isdigit() or len(gtin) != 8:
raise ValueError("GTIN must be an 8-digit number")
digits = [int(digit) for digit in gtin[:-1]]
check_digit = int(gtin[-1])
multiplied_digits = (
digits[0] * 3
+ digits[1]
+ digits[2] * 3
+ digits[3]
+ digits[4] * 3
+ digits[5]
+ digits[6] * 3
)
expected_check_digit = _round_up_ten(multiplied_digits) - multiplied_digits
if check_digit!= expected_check_digit:
raise ValueError("Incorrect check digit ({}) (expected {})".format(check_digit, expected_check_digit))
错误在行
if eightdigit == (gtin[7]):
eightdigit
是一个整数,但gtin[7]
是一个字符串。 因此,此比较始终是错误的-因此,您处于无限循环中(只要输入至少包含8个字符的字符串)。 您感到沮丧,然后只需按Enter键-它将空字符串(缺少第八个字符)传递给您的代码,从而触发索引超出范围错误。
因此,您将需要:
if eightdigit == int(gtin[7]):
来修复该特定错误,尽管这仍然会给您带来逻辑错误-因为代码底部的循环无法验证输入,并且您正在尝试根据先前输入计算出的校验位来检查新的候选gtins 。 您可能应该遵循@JacquesSupik的绝妙想法,并重构代码,以使验证逻辑与I / O逻辑分离。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.