运行我的代码时出现索引错误

时间:2016-05-21 10:31:19

标签: python indexing range

我是Python的新手,我正在编写一个程序,可以将七位数转换为带有校验位的GTIN-8代码。它允许我运行它,但在我输入我的号码后它给了我错误:

IndexError: String index out of range

我的代码如下:

sevenNum = ""
gtinNum = ""
checkDigit = ""
total = ""

a = 0
b = 0
c = 0
d = 0
e = 0
f = 0
g = 0

def GTINCalc():
    a = int(sevenNum[0])*3
    b = int(sevenNum[1])*1
    c = int(sevenNum[2])*3
    d = int(sevenNum[3])*1
    e = int(sevenNum[4])*3
    f = int(sevenNum[5])*1
    g = int(sevenNum[6])*3

    total = int(a+b+c+d+e+f+g)

    checkDigit = (total + 9) // 10 * 10 - total

    print("GTIN-8 Code: {0}{1}{2}{3}{4}{5}{6}{7}".format(a, b, c, d, e, f, g, checkDigit))


def sevenNumAsk():
    sevenNum = input("Enter a 7 digit number to be converted into a GTIN-8 Number")
    if sevenNum.isdigit() == True and len(sevenNum) == 7:
        print("Valid Number - Calculating GTIN-8...")
        GTINCalc()
    else:
        print("The number is not valid - please re-enter ")
        sevenNumAsk()

sevenNumAsk()

突出显示的部分是:

a = int(sevenNum[0])*3

感谢任何帮助。感谢。

1 个答案:

答案 0 :(得分:1)

sevenNumsevenNumAsk内的局部变量,不会影响您在顶部创建的全局变量。这样做:

def sevenNumAsk():
    global sevenNum
    sevenNum = ...

它将按预期行事。更好的是,使用类或传递sevenNum作为参数。全局变量通常很糟糕,这也是原因之一。