Amazing-Python-Scripts
64 строки · 1.6 Кб
1# Checking entered number is a isbn number or not
2def valid_ISBN(isbn):3# Remove hyphens and spaces from the ISBN4isbn = isbn.replace('-', '').replace(' ', '')5
6# Check if the length of the ISBN is valid7if len(isbn) == 10:8return valid_ISBN10(isbn)9elif len(isbn) == 13:10return valid_ISBN13(isbn)11else:12return False13
14# Checking the entered number is a valid 10-digit isbn number
15
16
17def valid_ISBN10(isbn):18# Check if the ISBN is valid according to the ISBN-10 algorithm19if not isbn[:-1].isdigit() or not isbn[-1] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'X']:20return False21
22# Calculate the check digit23checkDigit = 024weight = 1025for digit in isbn[:-1]:26checkDigit += int(digit) * weight27weight -= 128
29checkDigit %= 1130if isbn[-1] == 'X':31checkDigit = 'X'32
33# Validate the check digit34return str(checkDigit) == isbn[-1]35
36# Checking the entered number is a valid 13-digit isbn number
37
38
39def valid_ISBN13(isbn):40# Check if the ISBN is valid according to the ISBN-13 algorithm41if not isbn.isdigit():42return False43
44# Calculate the check digit45checkDigit = 046weight = [1, 3] * 647for digit, w in zip(isbn[:-1], weight):48checkDigit += int(digit) * w49
50checkDigit %= 1051checkDigit = (10 - checkDigit) % 1052
53# Validate the check digit54return str(checkDigit) == isbn[-1]55
56
57# Ask the user to enter an ISBN number
58isbnNumber = input("\nEnter an ISBN number: ")59
60# Validate the ISBN number
61if valid_ISBN(isbnNumber):62print("\nValid ISBN number.\n")63else:64print("\nInvalid ISBN number.\n")65