Skip to content

Instantly share code, notes, and snippets.

@samrose
Forked from corpit/upc_check_digit.py
Created September 10, 2020 13:18
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 samrose/a3658991d309b4e47ff4b2b11fdb0b21 to your computer and use it in GitHub Desktop.
Save samrose/a3658991d309b4e47ff4b2b11fdb0b21 to your computer and use it in GitHub Desktop.
Calculate UPC-A check digit in Python
def add_check_digit(upc_str):
"""
Returns a 12 digit upc-a string from an 11-digit upc-a string by adding
a check digit
>>> add_check_digit('02345600007')
'023456000073'
>>> add_check_digit('21234567899')
'212345678992'
>>> add_check_digit('04210000526')
'042100005264'
"""
upc_str = str(upc_str)
if len(upc_str) != 11:
raise Exception("Invalid length")
odd_sum = 0
even_sum = 0
for i, char in enumerate(upc_str):
j = i+1
if j % 2 == 0:
even_sum += int(char)
else:
odd_sum += int(char)
total_sum = (odd_sum * 3) + even_sum
mod = total_sum % 10
check_digit = 10 - mod
if check_digit == 10:
check_digit = 0
return upc_str + str(check_digit)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment