
Barcode Validator
Python Code Project
Barcodes are 12th digit numbers to identify products used worldwide. The last digit is a redundant check digit, used to catch errors. Using some simple calculations, a scanner can determine, given the first 11 digits, what the check digit must be for a valid code.
The goal of this Python code project is to write a Python program to check whether a barcode is valid based on the following rules:
- Sum the digits at odd-numbered positions (1st, 3rd, 5th, …, 11th).
- Multiply the result from step 1 by 3.
- Take the sum of digits at even-numbered positions (2nd, 4th, 6th, …, 10th) in the original number, and add this sum to the result from step 2.
- Find the result from step 3 modulo 10 (i.e. the remainder, when divided by 10) and call it M.
- If M is 0, then the check digit is 0; otherwise the check digit is 10 – M.
Expected ouput
Enter the first 11 digits of the barcode: 810012110099 The barcode is legitimate.
SOURCE CODE
# Step 1: Take Input
barcode = input("Enter the first 11 digits of the barcode: ")
# Step 2: Calculate Check Digit
odd_sum = sum(int(barcode[i]) for i in range(0, 11, 2)) # Sum of digits at odd-numbered positions
even_sum = sum(int(barcode[i]) for i in range(1, 11, 2)) # Sum of digits at even-numbered positions
result = (odd_sum * 3 + even_sum) % 10 # Result from step 4
check_digit = 0 if result == 0 else 10 - result # Calculated check digit
# Step 3: Check Validity
actual_check_digit = int(barcode[-1]) # Actual 12th digit of the barcode
is_legitimate = check_digit == actual_check_digit # Compare calculated check digit with actual check digit
# Step 4: Display Result
if is_legitimate:
print("The barcode is valid.")
else:
print("The barcode is not valid.")
For more Python projects, see here.