简体   繁体   English

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

[英]Having an index error when running my code

I am fairly new to Python and I am writing a program that can convert a seven digit number into a GTIN-8 code with a check digit also. 我对Python相当陌生,我正在编写一个程序,该程序也可以将7位数字转换为带有校验位的GTIN-8代码。 It allows me to run it, but after I enter my number it gives me the error: 它允许我运行它,但是输入我的号码后,它给了我错误:

IndexError: String index out of range

My code is as follows: 我的代码如下:

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()

The part that is highlighted is: 突出显示的部分是:

a = int(sevenNum[0])*3

Any help is appreciated. 任何帮助表示赞赏。 Thanks. 谢谢。

sevenNum is a local variable inside sevenNumAsk and doesn't affect the global variable you created at the top. sevenNum是内部的局部变量sevenNumAsk ,不会影响你在上面创建的全局变量。 Do this: 做这个:

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

and it will act as you expect. 它将如您所愿。 Better yet, use a class or pass sevenNum as a parameter. 更好的是,使用一个类或将sevenNum作为参数传递。 Global variables are generally bad and this is one of the reasons why. 全局变量通常是错误的,这就是原因之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM