Debug an ISBN Validator - Debug an ISBN Validator

Tell us what’s happening:

Can someone please help me? It is supposed to print Enter comma-separated values, but just don’t know what is going wrong.

I went over raise, try, except, else, finally statements, but I just got very confused, as I am struggling to understand the concepts for these error handling concepts. Personally, I would just use if-else and elif statements, but I just can’t do that because of the need to implement these concepts.

Your code so far

def validate_isbn(isbn, length):
    if len(isbn, length) != length:
        print(f'ISBN-{length} code should be {length} digits long.')
        return
    main_digits = isbn[0:length]
    given_check_digit = isbn[length]
    main_digits_list = [int(digit) for digit in main_digits]
    # 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:
        expected_check_digit = '0'
    elif result == 10:
        expected_check_digit = 'X'
    else:
        expected_check_digit = str(result)
    return expected_check_digit
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:
        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(',')
        if not len(values) == 2:
            raise ValueError('Enter comma-separated values.')
        isbn = values[0]
        length = int(values[1])
        if length == 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")
#main()

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36

Challenge Information:

Debug an ISBN Validator - Debug an ISBN Validator

1 Like

Have you uncommented main() and tested your code with different ISBN/length combinations? You’ll see error messages in the console that will help you know where to write error handling and/or guard clauses.

You may also want to review these theory lectures:

Understanding Error Handling - How Does Exception Handling Work? | Learn | freeCodeCamp.org

Understanding Error Handling - What Is the Raise Statement and How Does It Work? | Learn | freeCodeCamp.org

you can also put your code in a tool like https://pythontutor.com/ that execute the code line by like so you can see exactly where the issue is

Ok it seems like I got the code to work for the comma-separated sections. Now I am a bit confused on the length being a number. I used the same logic however I get “Length should be a number” for all inputs, even the valid ones. Can anyone help me out here:

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]
    given_check_digit = isbn[length]
    main_digits_list = [int(digit) for digit in main_digits]
    # 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:
        expected_check_digit = '0'
    elif result == 10:
        expected_check_digit = 'X'
    else:
        expected_check_digit = str(result)
    return expected_check_digit
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:
        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(',')
        if not len(values) == 2:
            raise ValueError('Enter comma-separated values.')
        isbn = int(values[0])
        length = int(values[1])
        if not isinstance(length, int):
            raise TypeError('Length must be a number.')
        else:
            if length == 10 or length == 13:
                 validate_isbn(isbn, length)
            else:
                print('Length should be 10 or 13.')
    except ValueError: print("Enter comma-separated values.")
    except TypeError: print("Length must be a number.")
main()

try to use the pythontutor to check what the code is doing line by line, you will figure it out

The user story says that the user aka the user you are requesting input from, should see the following messages in their terminal. “When the user does not enter a comma separated value, they should see the message Enter comma-separated values. in the console, and the program should terminate.”

what you have done is try to raise an error which would make the program crash without proper exception handling. if I am not mistaken.

You need to find the place where the original IndexError that the instructions request takes place. make an except block to handle it, send a message back to the “Users” Enter comma-separated values and then terminate the program, essentially write some code that stops the rest of the code from running. (this can be done easily I just don’t want to give the answer away)

I would suggest use the print() function to make a pseudo user input that lacks a comma, insert it into your code and see exactly what line the error comes from that needs to have an exception made for it. make that exception and see if that solves the problem.

What you essentially said here was: Length is equivalent to the integer value of (the 1st index of the list of values. Then your next line says in words: if length is not an integer raise an error. Does that make sense. You also need to be using exceptions here and not raise as per the instructions. Resolve the error, pass a message to the user, and then terminate the program without crashing it. Good luck to you on this project!