An ISBN (International Standard Book Number) can consist of 10 or 13 digits. The
ID: 3809783 • Letter: A
Question
An ISBN (International Standard Book Number) can consist of 10 or 13 digits. The
last digit is called checksum, which is calculated using a certain formula.
Calculations: ISBN-10
The ISBN-10 consists of 10 digits: 0718079183
The last digit is calculated using the first 9 digits as:
h = +×1+ /×2+ 1×3+ 3×4+ 5×5+ 7×6+ 9×7+ ;×8+ =×9 %11
If the checksum is 10, then the 10th digit is denoted as X.
Calculations: ISBN-13
The ISBN-13 consists of 13 digits: 9780718079185
h = 10 + +3 / + 1 +3 3 + 5 +3 7 + 9 +3 ; + = +3 +B + ++ +3 +/ %10
If the checksum is 10, then put 0 as the 13th digit.
Write a program that prompts the user to enter the digits (except the last digit) of an ISBN – it can be either ISBN-10 or ISBN-13. Read the input as a string. User can enter 9 digits or 12 digits. The program should determine the checksum based on the size of the number entered. If the user enters a number that doesn’t contain either 9 or 12 digits, display a message and prompt the user to enter 9 or 12 digits.
Sample Output:
Enter either 9 or 12 digits as a string (or -1 to quit): 9787312
Invalid ISBN number.
Enter either 9 or 12 digits as a string (or -1 to quit): 978071807918 The ISBN-13 number is: 9780718079185
Enter either 9 or 12 digits as a string (or -1 to quit): 0718079183 The ISBN-10 number is: 0718079183
Enter either 9 or 12 digits as a string (or -1 to quit): 013119402 The ISBN-13 number is: 013119402X
Enter either 9 or 12 digits as a string (or -1 to quit): 978731259722 The ISBN-13 number is: 9787312597220
it should be coded in python!
Explanation / Answer
# code link in case indentation mess up: https://goo.gl/58IDLm
def get_isbn10_checkbit(isbn):
check_bit = 0
counter_bit = 10
for i in isbn:
check_bit += counter_bit*i
counter_bit -= 1
check_bit = check_bit % 11
check_bit = 11 - check_bit
if check_bit == 10:
check_bit = 'X'
return check_bit
def get_isbn13_checkbit(isbn):
check_bit = 0
odd_sum = sum(isbn[0::2])
even_sum = sum(isbn[1::2])
even_sum = even_sum*3
check_bit = (even_sum + odd_sum)%10
if check_bit != 0:
check_bit = 10 - check_bit
return check_bit
isbn = ""
while True:
isbn = raw_input("Enter either 9 or 12 digits as a string (or -1 to quit): ")
if isbn == "-1":
break
if not (len(isbn) == 9 or len(isbn) == 12):
print "Invalid ISBN number."
continue
isbn_dig = [int(i) for i in isbn]
if len(isbn_dig) == 9:
check_bit = get_isbn10_checkbit(isbn_dig)
print "The ISBN-10 number is: "
else:
check_bit = get_isbn13_checkbit(isbn_dig)
print "The ISBN-13 number is: "
print isbn + str(check_bit)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.