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")
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
continuethe 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 acontinueto re-prompt the user: