Tell us what’s happening:
Just having a problem with none of my isbn’s coming out as valid.
Thanks for the tips.
Your code so far
def validate_isbn(isbn, length):
if len(isbn) != length:
print(f'ISBN-{length} code should be {length} digits long.')
return
main_digits = isbn[0:length+1]
print(main_digits)
given_check_digit = isbn[length-1]
print(given_check_digit)
try:
main_digits_list = [int(digit) for digit in main_digits]
except ValueError:
print('Invalid character was found.')
if length == 10:
expected_check_digit = calculate_check_digit_10(main_digits_list)
else:
expected_check_digit = calculate_check_digit_13(main_digits_list)
if given_check_digit == expected_check_digit:
print('Valid ISBN Code.')
else:
print('Invalid ISBN Code.')
def calculate_check_digit_10(main_digits_list):
digits_sum = 0
for index, digit in enumerate(main_digits_list):
digits_sum += digit * (10 - index)
print(digits_sum)
result = 11 - digits_sum % 11
print(result)
if result == 11:
expected_check_digit = '0'
elif result == 10:
expected_check_digit = 'X'
else:
expected_check_digit = str(result)
return expected_check_digit
print(expected_check_digit)
def calculate_check_digit_13(main_digits_list):
digits_sum = 0
for index, digit in enumerate(main_digits_list):
if index % 2 == 0:
digits_sum += digit * 1
else:
digits_sum += digit * 3
result = 10 - digits_sum % 10
if result == 10:
expected_check_digit = '0'
else:
expected_check_digit = str(result)
return expected_check_digit
def main():
user_input = input('Enter ISBN and length: ')
try:
values = user_input.split(',')
isbn = values[0]
length = int(values[1])
except IndexError:
print('Enter comma-separated values.')
return
except ValueError:
print('Length must be a number.')
return
try:
if length == 10 or length == 13:
validate_isbn(isbn, length)
else:
print('Length should be 10 or 13.')
return
except UnboundLocalError:
print('Length must be a number.')
return
main()
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36
Challenge Information:
Debug an ISBN Validator - Debug an ISBN Validator