Skip to content

Instantly share code, notes, and snippets.

@magdiel01
Created February 28, 2019 18:08
Show Gist options
  • Save magdiel01/cce595f3d228d22b87298021da44eb99 to your computer and use it in GitHub Desktop.
Save magdiel01/cce595f3d228d22b87298021da44eb99 to your computer and use it in GitHub Desktop.
Python function which verifies UPCs check digit
def calc_check_digit(value):
"""calculate UPCA and UPCE check digit"""
check_digit = 0
odd_pos = True
for char in str(value)[::-1]:
if odd_pos:
check_digit += int(char) * 3
else:
check_digit += int(char)
odd_pos = not odd_pos # alternate
check_digit = check_digit % 10
check_digit = 10 - check_digit
check_digit = check_digit % 10
return check_digit
def is_valid(upc):
return int(calc_check_digit(int(str(upc)[0:-1]))) == int(str(upc)[-1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment