Write a function called `is_valid_isbn(astring)` that takes the string entitled
ID: 3708494 • Letter: W
Question
Write a function called `is_valid_isbn(astring)` that takes the string entitled “astring” and returns the Boolean result of checking if astring is a valid ISBN (International Standard Book Number) number. The parameter “astring” has two common formats. One is “a-bcde-fghi-j,” and the other is “abcdefghij.” The first digit “a” denotes the country where the book is published or the language of the book. The digits “bcde” identify the publisher, the digits “fghi” the book, and the digit “j” represents the “check digit.” It value is such that
(10*a + 9*b + 8*c + 7*d + 6*e + 5*f + 4*g + 3*h + 2*i + j) mod 11 = 0
The character “X” is used for the digit j if j must be 10.
In python.
def is_valid_isbn(astring):
Explanation / Answer
def is_valid_isbn(astring):
#check length of string
if len(astring)!=10:
return False
#calculate the sum of first 9 digits
total=0
for i in range(len(astring)-1):
if int(astring[i])>=0 and int(astring[i])<=9:
total+=int(astring[i])*(10-i)
else:
return False
#check last digit if it is not equal to 'X' return false
if astring[9]!='X' and (int(astring[9])>=0 and int(astring[9])<=9):
return False
#add 10 to sum since last digit is 'X'
total+=10
rem=total%11
if rem==0:
return True
else:
return False
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.