Clink
Clink

Reputation: 3

My GTIN 8 check digit and validity check isn't working

My code supposed to ask for a 7 digit number (GTIN 8) and tell you the 8th digit and/or ask you for an 8 digit (GTIN 8) number and tell whether it's a valid GTIN 8 number. I am not getting these outputs though.

ERROR message when I type in a not 7 digit number

c = int(GTIN[2])*3

IndexError: string index out of range

ERROR message when I type in an 8 digit number

if len(str(GTIN))==8 and sum(total)%10==0:

TypeError: 'int' object is not iterable What do I need to do to my code to fix this error?

Thanks. This is my code (I can clarify anything you aren't sure about):

while 2>1:
    GTIN = input("Enter 7 digit number for check-digit. Enter 8 digit number for validity.")
if GTIN.isdigit()==False:
     continue

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

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

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

if len(GTIN) == 7:
    print("Your check digit is",checkdigit)

if len(str(GTIN))==8 and sum(total)%10==0:
    print("Valid GTIN-8 number")
else: print("Invalid GTIN number")

Upvotes: 0

Views: 3874

Answers (2)

Harry
Harry

Reputation: 1

To total up the numbers you can use a short list that you can use as the variable to calculate the check digit. I put mine like this:

num_sum  = num * 3 +num_1 + num_2 * 3 + num_3 + num_4 * 3 + num_5 + num_6 * 3

Then when you calculate you can use rounded - num_sum = check digit.

Upvotes: 0

idjaw
idjaw

Reputation: 26578

What I suggest doing here is to do some extra checking to ensure you have what you need. So, when you get the user input and you are checking for isdigit, make sure the length as well.

Furthermore, you should not use continue the way you have your condition set up. You should let the logic just proceed if it passes initial validation. So, instead, what you can do is check if it does not match the conditions and you can print an error message and then pass a continue to re-prompt the user:

if not GTIN.isdigit() or not len(GTIN) == 8:
    print("invalid entry...")
    continue

Upvotes: 0

Related Questions