Created
April 24, 2018 06:52
-
-
Save tonyallan/e8e55bfcf6868641dc323316603b1cb7 to your computer and use it in GitHub Desktop.
ISBN-10 and ISBN-13 Check-digit calculator
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
#!/usr/bin/env python3 | |
""" | |
https://en.wikipedia.org/wiki/International_Standard_Book_Number | |
Test values: | |
978-1-4860-1097-4 | |
0 9596129 9 8 | |
978-1-4405-9334-5 | |
1-4405-9334-5 | |
978-0-522-86467-0 | |
0-19-506160-8 | |
0-415-01011-X | |
More test data from http://www.unionsverlag.com/isbn_2/default.html | |
""" | |
while True: | |
try: | |
text = input('Enter an ISBN: ') | |
except EOFError: | |
break | |
if len(text) == 0: | |
break | |
isbn = '' | |
for char in text: | |
if char == ' ' or char == '-': | |
continue | |
isbn += char | |
if len(isbn) == 10: | |
i = 0 | |
total = 0 | |
while i < 9: | |
digit = int(isbn[i]) | |
total += digit * (i + 1) | |
i += 1 | |
if isbn[9] == 'x' or isbn[9] == 'X': | |
check = 10 | |
else: | |
check = int(isbn[9]) | |
calculated_check = (total % 11) | |
if calculated_check == check: | |
print('ISBN-10 {} is correct.'.format(text)) | |
else: | |
if calculated_check < 10: | |
check_char = str(calculated_check) | |
else: | |
check_char = 'X' | |
print('ISBN-10 {} contains an error. The calculated check character is {}.' \ | |
.format(text, check_char)) | |
elif len(isbn) == 13: | |
i = 0 | |
total = 0 | |
while i < 12: | |
digit = int(isbn[i]) | |
if (i % 2) == 0: | |
mod = 1 | |
else: | |
mod = 3 | |
total += (digit * mod) | |
i += 1 | |
check = int(isbn[12]) | |
calculated_check = (10 - total) % 10 | |
if calculated_check == check: | |
print('ISBN-13 {} is correct.'.format(text)) | |
else: | |
check_char = str(calculated_check) | |
print('ISBN-13 {} contains an error. The calculated check character is {}.' \ | |
.format(text, check_char)) | |
else: | |
print('ISBN must be 10 or 13 characters long.') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment