Debug an ISBN Validator - Debug an ISBN Validator

Tell us what’s happening:

Evening legends, i don’t know what i am getting wrong exactly but i am unable to validate the three Validate_isbn() that i commented out below in the code snippet.

Your code so far

class InvalidCharacterError(Exception):
    pass

def validate_isbn(isbn, length):
    if len(isbn) != length:
        if length == 10:
            print(f'ISBN-10 code should be 10 digits long.')
        else:
            print(f'ISBN-13 code should be 13 digits long.')    
        return

    main_digits = isbn[:-1]
    given_check_digit = isbn[-1]

    try:
        main_digits_list = [int(digit) for digit in main_digits]
    except ValueError:
        raise InvalidCharacterError
    # Calculate the check digit from other digits
    if length == 10:
        expected_check_digit = calculate_check_digit_10(main_digits_list)
    else:
        expected_check_digit = calculate_check_digit_13(main_digits_list)
    # Check if the given check digit matches with the calculated check digit
    if given_check_digit == expected_check_digit:
        print('Valid ISBN Code.')
    else:
        print('Invalid ISBN Code.')

def calculate_check_digit_10(main_digits_list):
    # Note: You don't have to fully understand the logic in this function.
    digits_sum = 0
    # Multiply each of the first 9 digits by its corresponding weight (10 to 2) and sum up the results
    for index, digit in enumerate(main_digits_list):
        digits_sum += digit * (10 - index)
    # Find the remainder of dividing the sum by 11, then subtract it from 11
    result = 11 - digits_sum % 11
    # The calculation result can range from 1 to 11.
    # If the result is 11, use 0.
    # If the result is 10, use upper case X.
    # Use the value as it is for other numbers.
    if result == 11:
        return '0'
    elif result == 10:
        return 'X'
    else:
        return str(result)

def calculate_check_digit_13(main_digits_list):
    # Note: You don't have to fully understand the logic in this function.
    digits_sum = 0
    # Multiply each of the first 12 digits by 1 and 3 alternately (starting with 1), and sum up the results
    for index, digit in enumerate(main_digits_list):
        if index % 2 == 0:
            digits_sum += digit * 1
        else:
            digits_sum += digit * 3
    # Find the remainder of dividing the sum by 10, then subtract it from 10
    result = 10 - digits_sum % 10
    # The calculation result can range from 1 to 10.
    # If the result is 10, use 0.
    # Use the value as it is for other numbers.
    if result == 10:
        return '0'
    else:
        return str(result)

def main():
    user_input = input('Enter ISBN and length: ')
    try:
        if ',' not in user_input:
            raise IndexError

        values = user_input.split(',')
        isbn = values[0].strip()
        length_str = values[1].strip()

        length = int(length_str)

        if legth == 10 or length == 13:
            validate_isbn(isbn, length)
        else:
            print('Length shouldshould be 10 or 13.')

    except IndexError:
        print('Enter comma-separated values.')
    except ValueError:
        print('Length must be a number.')
    except InvalidCharacterError:
        print('Invalid character was found.')
# main()

validate_isbn('1530051126', 10)
validate_isbn('1530051125', 10)
validate_isbn('9781530051120', 10)
#validate_isbn('15-0051126', 10)
validate_isbn('1530051126', 9)
#validate_isbn('1530051125', A)
#validate_isbn('1530051125')


Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36

Challenge Information:

Debug an ISBN Validator - Debug an ISBN Validator

Hi @justprecious1234,

Where are you checking to see if isbn contains invalid characters?

Also, you have some cleanup work to do here…typo and duplication.

Happy coding!

I commented the validate_isbn(‘15-0051126’, 10) so the traceback error will not crash my terminal.

About the typo error, it’s from FCC end not mine, I keep correcting the typo to length and the duplicates too but each time I minimize my browser and came back later, the typo error keep resurfacing

Morning dhess, haven’t got any reply from you yet.

please be patient, people are not constantly online

try saving your code with Ctrl+S before leaving the page/minimizing the browser

the question from dhess was about how you are dealing with invalid characters in the ISBN, considering that this one has invalid characters (what is the requirement for invalid characters?)

How am I dealing with invalid characters? I raise InvalidCharacterError in if valueError.

and what is the requirement for invalid characters? if you test by adding back main() and writing the input manually, does the app behave as expected?

Thanks for the prompt replies and guidance ILM, what do you mean by adding back main() and writing the input manually? i finally get to create an exception for invalid characters but the user-story is still not fulfilled in a way.

class InvalidCharacterError(Exception):
pass

def validate_isbn(isbn, length):
try:
num_length = int(length)
if len(isbn) != num_length:
if num_length == 10:
print(‘ISBN-10 code should be 10 digits long.’)
else:
print(‘ISBN-13 code should be 13 digits long.’)
return

    main_digits = isbn[:-1]
    given_check_digit = isbn[-1]
    
    if not main_digits.isdigit():
        raise InvalidCharacterError
    
    main_digits_list = [int(digit) for digit in main_digits]

# Calculate the check digit from other digits
    if num_length == 10:
        expected_check_digit = calculate_check_digit_10(main_digits_list)
    else:
        expected_check_digit = calculate_check_digit_13(main_digits_list) 

# Check if the given check digit matches with the calculated check digit
    if given_check_digit == expected_check_digit:
        print('Valid ISBN Code.')
    else:
        print('Invalid ISBN Code.')
    
except InvalidCharacterError:
    print('Invalid character was found.')
except (ValueError, TypeError):
    print('Length must be a number.')

def calculate_check_digit_10(main_digits_list):

Note: You don’t have to fully understand the logic in this function.

digits_sum = 0

Multiply each of the first 9 digits by its corresponding weight (10 to 2) and sum up the results

for index, digit in enumerate(main_digits_list):
digits_sum += digit * (10 - index)

Find the remainder of dividing the sum by 11, then subtract it from 11

result = 11 - digits_sum % 11

The calculation result can range from 1 to 11.

If the result is 11, use 0.

If the result is 10, use upper case X.

Use the value as it is for other numbers.

if result == 11:
return ‘0’
elif result == 10:
return ‘X’
else:
return str(result)

def calculate_check_digit_13(main_digits_list):

Note: You don’t have to fully understand the logic in this function.

digits_sum = 0

Multiply each of the first 12 digits by 1 and 3 alternately (starting with 1), and sum up the results

for index, digit in enumerate(main_digits_list):
if index % 2 == 0:
digits_sum += digit * 1
else:
digits_sum += digit * 3

Find the remainder of dividing the sum by 10, then subtract it from 10

result = 10 - digits_sum % 10

The calculation result can range from 1 to 10.

If the result is 10, use 0.

Use the value as it is for other numbers.

if result == 10:
return ‘0’
else:
return str(result)

def main():
user_input = input(‘Enter ISBN and length: ‘)
try:
values = user_input.split(’,’)
isbn = values[0].strip()
length_str = values[1].strip()

    length = int(length_str)

    if legth == 10 or length == 13:
        validate_isbn(isbn, length)
    else:
        print('Length should be 10 or 13.')

except IndexError:
    print('Enter comma-separated values.')
except ValueError:
    print('Length must be a number.')
except InvalidCharacterError:
    print('Invalid character was found.')

#main()

validate_isbn(‘1530051126’, 10)
validate_isbn(‘1530051125’, 10)
validate_isbn(‘9781530051120’, 10)
validate_isbn(‘15-0051126’, 10)
validate_isbn(‘1530051126’, 9)
validate_isbn(‘1530051125’, ‘A’)
#validate_isbn(‘1530051125’)
validate_isbn(‘hgyggggggg’, 10)
validate_isbn(‘9781530051120’, 13)

Uncomment main() and test ISBN and length combinations in the console against the “Example Inputs” in the instructions table.

Your task is not merely to write an exception. It’s to write code to see if ISBN contains invalid characters and if it does, you can raise an exception.

That said, there is no InvalidCharacterError. Please review the theory lectures for Understanding Error Handling. An invalid character should raise a ValueError since the invalid character is not part of the expected value.