Python Code to validate ISBNs

Giovanni

I wrote this simple piece of code to validate ISBN strings and I publish it because I hope it can be useful for someone else.

 Python |  Copy the following code |? 
01
# Copyright (C) 2011, Giovanni Di Milia
02
#
03
# This program is free software: you can redistribute it and/or modify
04
# it under the terms of the GNU General Public License as published by
05
# the Free Software Foundation, either version 3 of the License, or
06
# (at your option) any later version.
07
# 
08
# This program is distributed in the hope that it will be useful,
09
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
# 
13
# You should have received a copy of the GNU General Public License
14
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
15
 
16
def is_valid_isbn(isbn):
17
    """ 
18
        Function that validates ISBNs
19
        Based on 
20
        http://en.wikipedia.org/wiki/International_Standard_Book_Number
21
        @author: Giovanni Di Milia
22
    """
23
 
24
    #I remove the valid hyphens in the code if they exist
25
    isbn = isbn.replace('-', '')
26
 
27
    #Validation of ISBN 10
28
    if len(isbn) == 10:
29
        try:
30
            checksum = str(11 - ((int(isbn[0])*10 + int(isbn[1])*9 +\
31
                                 int(isbn[2])*8 + int(isbn[3])*7 + \
32
                                 int(isbn[4])*6 + int(isbn[5])*5 +\
33
                                int(isbn[6])*4 + int(isbn[7])*3 +\
34
                                 int(isbn[8])*2) % 11))
35
        except ValueError:
36
            #if I fails it means that there are letters, so the ISBN is not valid
37
            return False
38
 
39
        if checksum == '11':
40
            checksum = '0'
41
        elif checksum == '10':
42
            checksum = 'X'
43
        if checksum == isbn[9]:
44
            return True
45
        else:
46
            return False
47
    #Validation of ISBN 13
48
    elif len(isbn) == 13:
49
        try:
50
            checksum = str(10 - ((int(isbn[0]) + int(isbn[1])*3 + \
51
                                  int(isbn[2]) + int(isbn[3])*3 +\
52
                                   int(isbn[4]) + int(isbn[5])*3 +\
53
                                    int(isbn[6]) + int(isbn[7])*3  +\
54
                                    int(isbn[8]) + int(isbn[9])*3 + \
55
                                    int(isbn[10]) + int(isbn[11])*3) % 10))
56
        except ValueError:
57
            #if I fails it means that there are letters, so the ISBN is not valid
58
            return False
59
 
60
        if checksum == '10':
61
            checksum = '0'
62
        if checksum == isbn[12]:
63
            return True
64
        else:
65
            return False
66
    else:
67
        return False
68


Leave a Reply


four + = 8