Debug an ISBN Validator

Hi all,

I am having some trouble getting across the finish line for the challenge “Debug an ISBN Validator”.

Below is all of my code so far.

def validate_isbn(isbn, length):



    if len(str(isbn)) != int(length):

        print(f'ISBN-{length} code should be {length} digits long.')

    else:

        print('Valid ISBN Code.')



    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)

        raise ValueError('ISBN-10 code should be 10 digits long.')

    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():



    try:

        try:

            user_input = input('Enter ISBN and length: ')

            if ',' not in user_input:

                print('Enter comma-separated values.')

        except:

            print()



        values = user_input.split(',')

        

        try:

            isbn = int(values\[0\])



            if not isinstance(isbn, int):

                print('Invalid character was found.')

        except:

            print('Invalid character was found.')



        try:

            length = int(values\[1\])

            if length == 10 or length == 13:

                validate_isbn(isbn, length)

            else:

                print('Length should be 10 or 13.')

        except: 

            print('Length must be a number.')



    except (IndexError, ValueError) as e:

        print(f'{e}')



main()

I realize this is not the most concise or pretty structure for the code, I am still very new to this. Error logging as always given me trouble.

The two final challenges I have are:

  1. When the user enters 1530051125,10, you should see the message Invalid ISBN Code.
  2. When the user enters 080442957X,10, you should see the message Valid ISBN Code.

I have everything else checked off. I am using VS Code to help debug this. I’m mostly confused about how to trigger the calculation for the 10 or 13 digit check that happens on the last digit of the ISBN.

Looking for some advice and where to look as I have been stuck on these ones for a few days. Any help is greatly appreciated.

Thank you!

Please Tell us what’s happening in your own words.

Learning to describe problems is hard, but it is an important part of learning how to code.

Also, the more you say, the more we can help!

Hi! Thanks for the response. I just updated the post. This was my first one on the website so I wasn’t sure how the posting process worked.

Thanks!

I’ve edited your post to improve the readability of the code. When you enter a code block into a forum post, please precede it with three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add the backticks.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

Much appreciated, thank you! I will know for next time.

Can you please share a link to the lab you are working on?

Here are some troubleshooting steps you can follow. Focus on one test at a time:

  1. Are there any errors or messages in the console?
  2. What is the requirement of the first failing test?
  3. Check the related User Story and ensure it’s followed precisely.
  4. What line of code implements this?
  5. What is the result of the code and does it match the requirement? (Write the value of a variable to the console at that point in the code if needed.)

If this does not help you solve the problem, please reply with answers to these questions.

Hi, my apologies but I can’t seem to edit my original post anymore. I have attached the link at the top of my reply here.

Below are my responses to your questions:

  1. The only errors in the console are
    // running tests
    11. When the user enters 1530051125,10, you should see the message Invalid ISBN Code..
    19. When the user enters 080442957X,10, you should see the message Valid ISBN Code..
    // tests completed

  2. The requirement of the first test failing is that that 1520051125,10 should trigger the message “Invalid ISBN Code.” as mentioned in answer #1.

  3. I have followed the user stories for these two scenarios, although they are quite quite vague and the user story is just a statement of the requirement worded differently.

  4. I believe there should be something to trigger the calculate_check_digit_10 (or 13) code if the previous requirements are met, but through debugging on VS Code it skips those functions entirely and I can’t seem to pinpoint the exact area where I should be getting that trigger to happen.

  5. The result of running the code and using 1530051125, 10 is this:

    “Enter ISBN and length:
    1530051125,10
    Valid ISBN Code.
    Length must be a number.”

I hope I was able to answer your questions. Again, still new to coding and understanding exactly how this error logging should function in the code. Happy to try and elaborate further if required.

Appreciate the help!

1 Like

The given length, 10, is a number, right?

Can you please share the block of code that handles checking the length input?

User Story 5 doesn’t seem that vague

When the user enters a non-numeric value for the length, they should see the message Length must be a number. in the console,

def main():
    try:
        try:
            user_input = input('Enter ISBN and length: ')
            if ',' not in user_input:
                print('Enter comma-separated values.')
        except:
            print()

        values = user_input.split(',')
        
        try:
            isbn = int(values[0])

            if not isinstance(isbn, int):
                print('Invalid character was found.')
        except:
            print('Invalid character was found.')

        try:
            length = int(values[1])
            if length == 10 or length == 13:
                validate_isbn(isbn, length)
            else:
                print('Length should be 10 or 13.')
        except: 
            print('Length must be a number.')

    except (IndexError, ValueError) as e:
        print(f'{e}')

In my except block in the main() method, I am printing the statement “Length must be a number”. I realize this is likely the wrong place to have it (if I have it at all) and was from earlier testing to see what was happening when I ran the code. The statement will currently print even if the ISBN is correct.

The code for checking the length input is done here:

        try:
            length = int(values[1])
            if length == 10 or length == 13:
                validate_isbn(isbn, length)
            else:
                print('Length should be 10 or 13.')
        except: 
            print('Length must be a number.')

What I am trying to figure out is how to trigger the statement in the validate(isbn, length) method when the ISBN is invalid. For example, 1530051125,10 and 1530051126,10 as user input will both produce “Valid ISBN Code.” as well as “Length must be a number.” due to my print statement mentioned above. But, the ISBN ending in 1125 should be invalid while 1126 is valid.

I think you’re overusing try/except and it’s confusing what blocks of code are running and what aren’t and why.

Try taking all of those out and investigating further. Don’t use that as a magic wand to avoid all errors.

1 Like

I started over and read everything very slowly. I also took into account your suggestion of the overuse of try-except blocks.

I am happy to say I figured this one out and was able to successfully pass all tests.

Thank you for the advice!

1 Like

That’s fantastic, nice work!

It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge. How to Help Someone with Their Code Using the Socratic Method

We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.

Please do not reply to older threads that are already solved.