Validating barcodes

June 1, 2012

Here is some Python to validate barcodes (tested with EAN-13s). Someone should find it useful.

get_check_digit() will generate the valid check digit for the first part of a barcode. While is_valid_barcode() will check the final digit of a barcode against the generated check digit.

import math

def get_check_digit(b):
    """
    Returns the check digit for a barcode.
    
    It is assumed that the check digit is missing from the input.
    """
    sum = 0
    for x, c in enumerate(b[::-1]):
        if (x + 1) % 2:
            sum += int(c) * 3
        else:
            sum += int(c)
    return str(int(math.ceil(sum / 10.0) * 10) - sum)

def is_valid_barcode(b):
    """
    Checks the last digit of a barcode matches the calculated 
    check digit.
    """
    return get_check_digit(b[0:-1]) == b[-1]

test_data = (
    # Valid barcodes
    ('9771473968012', True),
    ('0123456789012', True),
    ('1234567890128', True),
    # Invalid barcodes
    ('9771473968011', False),
    ('0123456789019', False),
    ('1234567890127', False),
)

for t in test_data:
    print t[1] == is_valid_barcode(t[0])

Categories: Programming, Python

View Comments

blog comments powered by Disqus