I'm trying to return the ISBN-13 check digit from a 12-digit ISBN but have encountered a bizarre error.
Take the following as my 12-digit ISBN - 978311020318
Each digit is alternatively multiplied by 1 or 3.
9*1 + 7*3 + 8*1 + 3*3 + 1*1 + 1*3 + 0*1 + 2*3 + 0*1 + 3*3 + 1*1 + 8*3 = 91
91 % 10 = 1
10 - 1 = 9, which is our ISBN-13 check digit.
This is what I have so far...
def isbn_check_digit(isbn):
s = 0
for i, d in enumerate(isbn):
if i % 2 == 0:
s += int(d*1)
else:
s += int(d*3)
print(s)
return (10 - (s % 10))
print(isbn_check_digit("978311020318"))
Which outputs the following...
786
1127
1239
1461
1794
2683
7
I broke it up to see what was happening
if i % 2 == 0:
s += int(d*1)
print(s)
else:
s += 0
9
17
18
18
18
19
1
Multiples of 1 are working fine, but why is it behaving strangely with multiples of 3?
Because, at the time that the expression int(d * 3)
is evaluated, d
is not a number — it's a string consisting of one character, which is a digit. As a result, "multiplying" it by 3 will repeat the digit three times: for instance, 3
will turn into 333
, rather than 9
.
You want to multiply by 3 after converting the string to an integer:
int(d) * 3