Implement a Python program that simulates a library system where users can borrow books. Raise custom exceptions for scenarios like book not found, book already borrowed, user has too many books, etc.
Example 1:
Input: Library: {"book1": {"borrowed": False}, "book2": {"borrowed": True}}, User: {"name": "user1", "books": []}, Book: "book1" Output: "Book borrowed successfully."
Example 2:
Input: Library: {"book1": {"borrowed": False}, "book2": {"borrowed": True}}, User: {"name": "user1", "books": ["book3", "book4", "book5"]}, Book: "book1" Output: "Error: User has too many books."
Use dictionaries to store the library and user information.
def borrow_book(library, user, book): if book not in library: raise Exception("Error: Book not found.") elif library[book]["borrowed"]: raise Exception("Error: Book already borrowed.") elif len(user["books"]) >= 3: raise Exception("Error: User has too many books.") else: library[book]["borrowed"] = True user["books"].append(book) return "Book borrowed successfully." library = {"book1": {"borrowed": False}, "book2": {"borrowed": True}} user = {"name": "user1", "books": []} print(borrow_book(library, user, "book1")) # Output: "Book borrowed successfully." print(borrow_book(library, user, "book2")) # Output: "Error: Book already borrowed."
Unlock AI & Data Science treasures. Log in!