Reputation: 1
I am a beginner in coding and am trying to write this GTIN-8 code on python but it keep saying invalid syntax. Please help me. Thank you. BTW, it would be great if you could give me some advices on making the code more efficient and other constructive criticisms. Thank you.
DigitNumber = input ("Enter 7 different digit: ")
length=len(DigitNumber)
while length != 7:
print("Please type 7 digit codes.")
DN= input ("Enter 7 different digit: ")
if(length==7):
GTIN1=int(DigitNumber[0])
GTIN2=int(DigitNumber[1])
GTIN3=int(DigitNumber[2])
GTIN4=int(DigitNumber[3])
GTIN5=int(DigitNumber[4])
GTIN6=int(DigitNumber[5])
GTIN7=int(DigitNumber[6])
TOTALGTIN=int(GTIN1*3+GTIN2+GTIN3*3+GTIN4+GTIN5*3+GTIN6+GTIN7*3)
roundingup=round(TOTALGTIN, -1)
GTIN8 = int(roundingup - TOTALGTIN) % 10
print("The full valid 8-Digit GTIN-8 code is: "+str(DigitNumber)+str(GTIN8)
yes = set(['yes','y', 'ye'])
no = set(['no','n'])
choice = input("Would you like to validate your 8-digit GTIN-8code?")
if choice in yes:
Validate = input("Enter your 8 digit GTIN-8 number: ")
GTIN1=int(DigitNumber[0])
GTIN2=int(DigitNumber[1])
GTIN3=int(DigitNumber[2])
GTIN4=int(DigitNumber[3])
GTIN5=int(DigitNumber[4])
GTIN6=int(DigitNumber[5])
GTIN7=int(DigitNumber[6])
GTIN8=int(DigitNumber[7])
Validifying=int(GTIN1*3+GTIN2+GTIN3*3+GTIN4+GTIN5*3+GTIN6+GTIN7*3+GTIN8)
Check=Validifying%10
if(Validifying/10.).is_integer():
print("Your code is valid")
else:
print("Your 8 digit GTIN code is invalid.")
elif choice in no:
print ("Ok, thank you.")
exit(1)
else:
sys.stdout.write("Please respond with 'yes' or 'no'")
Upvotes: 0
Views: 479
Reputation: 21956
GS1 codes come in different lengths, ranging from GTIN-8 (8 digits) to SSCC (2 digit application ID + 18 digits). Here's a simple, general Python formula that works for any length GS1 identifier:
cd = lambda x: -sum(int(v) * [3,1][i%2] for i, v in enumerate(str(x)[::-1])) % 10
(10 - (sum mod 10)) mod 10
approach you'd get if you follow the GS1 manual calculation outline exactly, but that's ugly.## GTIN-8
>>> cd(1234567)
0
>>> cd(9505000)
3
## GTIN-12
>>> cd(71941050001)
6
>>> cd('05042833241')
2
## GTIN-13
>>> cd(900223631103)
6
>>> cd(501234567890)
0
## GTIN-14
>>> cd(1038447886180)
4
>>> cd(1001234512345)
7
## SSCC (20 digits incl. application identifier)
>>> cd('0000718908562723189')
6
>>> cd('0037612345000001009')
1
Upvotes: 1