所以我需要编写一个程序,为用户提供两个选项:A)验证GTIN代码或B)从7个GTIN代码中查找GTIN代码的8位数。我有代码,但它唯一的问题是,它是不是要求用户选择像A)你想要找到第8位或B)你想要验证代码 每当用户选择他或她的选项时,它应该仅针对该选项而不是整个代码执行for循环。如果有人知道如何将它放入菜单中,请告诉我,谢谢。
gtin = input("Enter your 7 digit number")
sum = 0
counter = 0
for i in gtin:
counter = counter + 1
if counter % 2 != 0:
sum = sum + int(i) * 3
else:
sum = sum + int(i) * 1
number = (sum + 9) // 10 * 10
lastdigit = number - sum
print("8th digit ", lastdigit)
print("Full 7 digit number ", gtin)
print("Full 8 digit number ", str(gtin+str(lastdigit)) )
barcode = input("Please enter 8 digit barcode to validate")
for i in gtin:
counter = counter + 1
if counter % 2 != 0:
sum = sum + int(i) * 3
else:
sum = sum + int(i) * 1
if sum % 10 == 0:
print("Valid GTIN")
else:
print("Invalid GTIN")
答案 0 :(得分:0)
您打算做的代码可以是这样的:
print ("Choose:")
print ("1. Validate GTIN Code")
print ("2. Find 8 digit of GTIN code")
user_input = input("Select 1 or 2")
if user_input == 1:
# execute validate GTIN code
elif user_input == 2:
# execute find 8 digit gtin code
else:
print ("please enter a valid option")
希望它有所帮助。
编辑: 粘贴整个代码
print("Choose:")
print("1. Validate GTIN Code")
print("2. Find 8 digit of GTIN code")
sum = 0
counter = 0
user_input = input("Select 1 or 2")
if user_input == 1:
gtin = input("Enter your 7 digit number")
for i in gtin:
counter = counter + 1
if counter % 2 != 0:
sum = sum + int(i) * 3
else:
sum = sum + int(i) * 1
number = (sum + 9) // 10 * 10
lastdigit = number - sum
print("8th digit ", lastdigit)
print("Full 7 digit number ", gtin)
print("Full 8 digit number ", str(gtin+str(lastdigit)) )
elif user_input == 2:
barcode = input("Please enter 8 digit barcode to validate")
for i in gtin:
counter = counter + 1
if counter % 2 != 0:
sum = sum + int(i) * 3
else:
sum = sum + int(i) * 1
if sum % 10 == 0:
print("Valid GTIN")
else:
print("Invalid GTIN")
else:
print "please enter a valid option"
答案 1 :(得分:0)