Exercise 12-07:

Write a program that validates user data entry. It will validate ISBNs (International Standard Book Numbers), which are used to identify books worldwide.
The program must accept ISBNs in the following format: ISBN 999-9-99-999999-9, where each 9 represents a digit.
The ISBN letters are optional and be case-insensitive. The space between N and the first number is mandatory if the ISBN is present. Require the dashes as in the example, verifying the correct number of digits.

Valid values:
ISBN 123-3-12-123456-1
Isbn 123-3-12-123456-1
123-3-12-123456-1

Invalid values:
ISBN123-3-12-123456-1
ISBN 1233-12123456-1

Answer:

##############################################################################
# Python From Scratch
# Author: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2025 - LogiKraft 2025
# Site: https://pythonfromscratch.com
# ISBN: 978-85-7522-949-1 (Paperback), 978-85-7522-950-7 (hardcover), 978-85-7522-951-4 (ebook)
#
# File: chapter 12/exercise-12-07.py.py
##############################################################################

import re


def validate_isbn(isbn):
    # Regex pattern to validate the ISBN format
    # ^ - start of string
    # (?:ISBN\s+)? - optional "ISBN" followed by at least one space
    # \d{3}-\d{1}-\d{2}-\d{6}-\d{1} - specific format with hyphens
    # $ - end of string
    # flags=re.IGNORECASE - ignore case for "ISBN"
    pattern = r"^(?:ISBN\s+)?\d{3}-\d{1}-\d{2}-\d{6}-\d{1}$"

    return re.match(pattern, isbn, flags=re.IGNORECASE)


print("Enter ISBNs for validation (or 'exit' to quit)")
print("Expected format: ISBN 999-9-99-999999-9\n")

while True:
    isbn_input = input("Enter an ISBN: ").strip()

    # Check if the user wants to exit
    if isbn_input.lower() in ["sair", "exit", "quit", "q"]:
        print("Program terminated.")
        break

    # Validate the ISBN
    if validate_isbn(isbn_input):
        print("✓ VALID ISBN\n")
    else:
        print("✗ INVALID ISBN")
        print("   Expected format: ISBN 999-9-99-999999-9")
        print("   Example: ISBN 123-3-12-123456-1\n")
Click here to download the file