Drill

ProblemsPython › validation

Verify a barcode

mediumvalidationPython

A scanner sometimes misreads a digit. The EAN-13 check digit catches most of those before the wrong product reaches the basket.

barcode_valid(code: string) → bool

Solve it in the editor →

Where you start

def barcode_valid(code: str) -> bool:
    

Worked examples

CallResult
barcode_valid("4006381333931")True
barcode_valid("4006381333932")False
barcode_valid("400638133393")False
barcode_valid("400638133393a")False

Hint

The check digit is the thirteenth and takes part in the sum like any other.

Reference solution in Python
def barcode_valid(code: str) -> bool:
    if len(code) != 13 or not code.isdigit():
        return False
    total = 0
    for i, c in enumerate(code):
        d = int(c)
        total += d if i % 2 == 0 else d * 3
    return total % 10 == 0

The same problem in another language

More validation problems in Python