Created
January 1, 2014 02:59
-
-
Save corpit/8204593 to your computer and use it in GitHub Desktop.
Calculate UPC-A check digit in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
@sxflynn The check digit is designed with that exact scenario in mind.
With a check digit, one can detect simple errors in the input of a series of characters (usually digits) such as a single mistyped digit or some permutations of two successive digits.
https://en.wikipedia.org/wiki/Check_digit
When the check digit is incorrect, the UPC length is incorrect, or a non-int character is found (line 23 or 25) this function should raise an exception. Trying to fix the users error in this function would be considered bad practice.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What if the user mistakingly enters a non-int character in the string of 12 digits? Such as 042100o05264