djjordand6 djjordand6 - 6 months ago 42
Python Question

Integer to String error in my program

I am having a problem with a program I am currently working on. It is a GTIN-8 Code generator. When I try to start the program, I get the error: Type Error: Can't convert 'int' to str implicitly.

My code is as follows:

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

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

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

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

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

print("GTIN-8 Code:" + 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()


I am having problems with this part:

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

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


Many thanks.

Answer

You cannot concatenate string and ints together:

print("GTIN-8 Code:" + a+b+c+d+e+f+g+checkDigit)

It is more correct to use string formatting anyway, for example:

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