Barcode Validator Project

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:

  1. Sum the digits at odd-numbered positions (1st, 3rd, 5th, …, 11th).
  2. Multiply the result from step 1 by 3.
  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.
  4. Find the result from step 3 modulo 10 (i.e. the remainder, when divided by 10) and call it M.
  5. 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.

We will be happy to hear your thoughts

Leave a reply

Python and Excel Projects for practice
Register New Account
Shopping cart