Files
exercism_puzzles/python/isbn-verifier/isbn_verifier.py
T

25 lines
923 B
Python

def is_valid(isbn):
# remove dashes
isbn_no_dashes: str = "".join(isbn.split("-"))
sum: int = 0
# is isbn empty
if isbn == "":
return False
# isbn length must be 10
if len(isbn_no_dashes) < 10 or len(isbn_no_dashes) > 10:
return False
for index, digit in enumerate(isbn_no_dashes):
# non-digit in isbn not as a checksum, return False
if digit.isalpha() and index != 9:
return False
# if its a digit, ok
if digit.isdigit():
sum += int(digit) * (10 - index)
# if check digit is not digit or not an 'X', return False
if index == 9 and digit.isalpha() and digit.lower() != "x":
return False
# if check digit is the letter 'X' treat it as a 10
if digit.isalpha() and index == 9 and digit.lower() == "x":
sum += 10 * (10 - index)
return False if sum % 11 else True