How can I check if a string is a valid ISBN-10 number in Python?
Ava W
ava w profile pic

To check if a string is a valid ISBN-10 number in Python, you can follow these steps: 1. Define a function to check if the string is a valid ISBN-10 number:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

   def is_valid_isbn_10(isbn):
  # Remove hyphens and whitespace from the ISBN string
  isbn = isbn.replace('-', '').replace(' ', '')

  # Check if the length of the ISBN is valid
  if len(isbn) != 10:
 return False

  # Check if the first 9 characters are digits
  if not isbn[:-1].isdigit():
 return False

  # Calculate the check digit
  check_digit = 0
  for i, digit in enumerate(isbn[:-1]):
 check_digit += int(digit) * (10 - i)
  check_digit = (11 - (check_digit % 11)) % 11

  # Compare the check digit with the last character of the ISBN
  if str(check_digit) == isbn[-1] or (check_digit == 10 and isbn[-1] == 'X'):
 return True

  return False
   

2. Call theis_valid_isbn_10 function and pass the string to be checked:

1
2
3
4
5
6
7

   isbn = "0-306-40615-2"
   if is_valid_isbn_10(isbn):
  print("Valid ISBN-10 number")
   else:
  print("Invalid ISBN-10 number")
   

In theis_valid_isbn_10 function, the string is first modified to remove any hyphens or whitespace characters using thereplace() method. This ensures that only the digits and 'X' (for the check digit) remain. The function then performs several checks to validate the ISBN-10 number: - It checks if the length of the ISBN is exactly 10 characters. - It verifies that the first 9 characters are digits using theisdigit() method. - It calculates the check digit by summing the product of each digit with its corresponding weight (10, 9, ..., 2) using a loop. - It applies the formula(11 - (check_digit % 11)) % 11 to calculate the final check digit. - Finally, it compares the calculated check digit with the last character of the ISBN. If the check digit matches the last character (or 'X' in the case of 10), the function returnsTrue, indicating that the ISBN-10 number is valid. You can modify the code to include any additional checks or handle specific requirements for ISBN-10 validation. Use theis_valid_isbn_10 function to check if a string is a valid ISBN-10 number in your Python programs.