Skip to content

Instantly share code, notes, and snippets.

@02015678
Created April 26, 2015 11:33
Show Gist options
  • Save 02015678/049382928d96e3648d50 to your computer and use it in GitHub Desktop.
Save 02015678/049382928d96e3648d50 to your computer and use it in GitHub Desktop.
Check ISBN Validity (Just check if the last bit is not conflict with the algorithm)
# Copyright (C) 2011, Giovanni Di Milia
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
def is_valid_isbn(isbn):
"""
Function that validates ISBNs
Posted on
http://www.dimilia.it/2011/09/02/python-code-to-validate-isbns/
Based on
http://en.wikipedia.org/wiki/International_Standard_Book_Number
@author: Giovanni Di Milia
"""
#I remove the valid hyphens in the code if they exist
isbn = isbn.replace('-', '')
#Validation of ISBN 10
if len(isbn) == 10:
try:
checksum = str(11 - ((int(isbn[0])*10 + int(isbn[1])*9 +\
int(isbn[2])*8 + int(isbn[3])*7 + \
int(isbn[4])*6 + int(isbn[5])*5 +\
int(isbn[6])*4 + int(isbn[7])*3 +\
int(isbn[8])*2) % 11))
except ValueError:
#if I fails it means that there are letters, so the ISBN is not valid
return False
if checksum == '11':
checksum = '0'
elif checksum == '10':
checksum = 'X'
if checksum == isbn[9]:
return True
else:
return False
#Validation of ISBN 13
elif len(isbn) == 13:
try:
checksum = str(10 - ((int(isbn[0]) + int(isbn[1])*3 + \
int(isbn[2]) + int(isbn[3])*3 +\
int(isbn[4]) + int(isbn[5])*3 +\
int(isbn[6]) + int(isbn[7])*3 +\
int(isbn[8]) + int(isbn[9])*3 + \
int(isbn[10]) + int(isbn[11])*3) % 10))
except ValueError:
#if I fails it means that there are letters, so the ISBN is not valid
return False
if checksum == '10':
checksum = '0'
if checksum == isbn[12]:
return True
else:
return False
else:
return False
# Here are some samples
print is_valid_isbn("0-9553010-0-9")
print is_valid_isbn("978-0-9553010-0-1")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment