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. It allows me to run it, but after I enter my number it gives me the error:
我是Python的新手,我正在编写一个程序,可以将七位数转换为带有校验位的GTIN-8代码。它允许我运行它,但在我输入我的号码后它给了我错误:
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.
任何帮助表示赞赏。谢谢。
1 个解决方案
#1
1
sevenNum
is a local variable inside sevenNumAsk
and doesn't affect the global variable you created at the top. Do this:
sevenNum是sevenNumAsk中的局部变量,不会影响您在顶部创建的全局变量。做这个:
def sevenNumAsk():
global sevenNum
sevenNum = ...
and it will act as you expect. Better yet, use a class or pass sevenNum
as a parameter. Global variables are generally bad and this is one of the reasons why.
它会像你期望的那样行事。更好的是,使用类或传递sevenNum作为参数。全局变量通常很糟糕,这也是原因之一。
#1
1
sevenNum
is a local variable inside sevenNumAsk
and doesn't affect the global variable you created at the top. Do this:
sevenNum是sevenNumAsk中的局部变量,不会影响您在顶部创建的全局变量。做这个:
def sevenNumAsk():
global sevenNum
sevenNum = ...
and it will act as you expect. Better yet, use a class or pass sevenNum
as a parameter. Global variables are generally bad and this is one of the reasons why.
它会像你期望的那样行事。更好的是,使用类或传递sevenNum作为参数。全局变量通常很糟糕,这也是原因之一。