We've been asked to code a program which validate GTIN-8 codes. The valdation is as follows:
Multiply the first 7 digits alternately by 3 then 1
Add them up
Subtract that number from the equal or higher multiple of 10
The resulting number is the eighth digit
Here's my code:
def validgtin():
gtin = input("Enter the 8 digits of GTIN-8 product code: ")
valid = False
while valid == False:
if gtin.isdigit():
gtin = str(gtin)
if len(gtin) == 8:
valid = True
else:
print("That is not correct, enter 8 digits, try again: ")
gtin = input("Enter the 8 digits of GTIN-8 product code: ")
else:
print("That is not correct, type in numbers, try again: ")
gtin = input("Enter the 8 digits of GTIN-8 product code: ")
sumdigit = 3*(int(gtin[0])) + 1*(int(gtin[1])) + 3*(int(gtin[2])) + 1*(int(gtin[3])) + 3*(int(gtin[4])) + 1*(int(gtin[5])) + 3*(int(gtin[6])) #sum of the digits
gtin = str(gtin)
valid1 = False
while not valid1:
if sumdigit%10 == 0:
eightdigit = 0
else:
eightdigit = (((sumdigit + 10)//10)*10) - sumdigit
if eightdigit == (gtin[7]):
valid1 = True
print("Your GTIN-8 product code is valid.")
else:
print("Your GTIN-8 product code is not valid.")
gtin = input("Enter the 8 digits of GTIN-8 product code: ")
return
validgtin()
When I run this code and type an invalid GTIN-8 code it says that the code is invalid and prompts me to type in a new GTIN-8 code
BUT
After I type in a new and valid GTIN-8 code it still says it is invalid
AND
After that this happens:
Traceback (most recent call last):
File "C:\Users\Yash Dwivedi\Documents\Year 10\GCSE Computing\Assignment\Task 1 v2.py", line 29, in validgtin
if eightdigit == (gtin[7]):
IndexError: string index out of range
I don't understand why I'll be thankful for any help.
gtin = str(gtin)? That would make some sense in Python 2 -- but then it that case you should be usingraw_input. On the other hand, if this is Python 2 thengtin.isdigit()would throw a runtime error if the user had in fact entered something consisting of exclusively digits.