Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
5001CEM_bookshop/isbn13.py
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
67 lines (50 sloc)
1.84 KB
This file contains 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 check_isbn13(isbn, debugging=False): | |
""" | |
# Since ISBN13s have 978 at the start, we can check for this and calculate it seperately. | |
Also, we dont need any hyphens as the order of hyphens does not matter after the first one. | |
https://isbn-information.com/the-13-digit-isbn.html | |
""" | |
isbn_str = remove_hyphens(str(isbn)) | |
if len(isbn_str) != 13: | |
if debugging: | |
print("isbn13 check: Invalid length") | |
return False | |
if debugging: | |
print(isbn, isbn_str) | |
first_three = isbn_str[:3] | |
if first_three != "978": | |
return False | |
remaining = isbn_str[3:-1] | |
base, tripled, normal = 38, 0, 0 # 38 is the constant from calculating values from the starting 978 | |
if debugging: | |
print("\nSTATUS", "i", "x", "x*3") | |
for i in range(0, len(remaining)): | |
if (i + 1) % 2 == 1: | |
tripled = tripled + int(remaining[i]) * 3 | |
if debugging: | |
print("TRIPLE", i, remaining[i], int(remaining[i]) * 3) | |
else: | |
normal = normal + int(remaining[i]) | |
if debugging: | |
print("NORMAL", i, remaining[i], remaining[i]) | |
total = base + tripled + normal | |
check_digit = int(isbn_str[12]) # last character of the ISBN provided | |
mod = total % 10 | |
if debugging: | |
print("\n100 mod", total, "=", mod) | |
calculated_digit = 10 - mod | |
if debugging: | |
print("calculation:", calculated_digit, "\nlast character:", check_digit) | |
if calculated_digit == check_digit: | |
if debugging: | |
print("\nEQUAL\n==========") | |
return True | |
else: | |
if debugging: | |
print("\nNOT EQUAL\n==========") | |
return False | |
def remove_hyphens(text, debugging=False): | |
out_text = text.replace("-", "") | |
if debugging: | |
print(text, ">>>", out_text) | |
return out_text | |