Skip to content

Instantly share code, notes, and snippets.

@xv
Last active April 2, 2023 17:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xv/296d2cdedac88d54cdcd4dc643dfedcb to your computer and use it in GitHub Desktop.
Save xv/296d2cdedac88d54cdcd4dc643dfedcb to your computer and use it in GitHub Desktop.
Python function to calculate the check digit of a UPC-12 barcode.
def calc_check_digit(digits):
digits = [int(i) for i in str(digits)][:-1]
odd_pos_list = digits[0::2] # 1st, 3rd, 5th, etc
even_pos_list = digits[1::2] # 2nd, 4th, 6th, etc
n = (sum(odd_pos_list) * 3) + sum(even_pos_list)
rmndr = n % 10
return (10 - rmndr) if rmndr > 0 else 0
# Full 12 digits of a UPC-12 barcode
digits = '123601057072'
check_digit = calc_check_digit(digits)
# Return value should match the 12th digit on the barcode
print(check_digit)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment