Design and implement a console-based Library Book Management System in Python. The
system should store available books in a dictionary, where each key represents a book title
(string) and the corresponding value represents the number of copies available (integer). The
program must allow the user to borrow books by entering the book name and the number of
copies they wish to borrow. If the entered book name does not exist in the dictionary, handle
the situation using a KeyError exception and display an appropriate message. If the user enters
a non-integer value for the number of copies, handle it using a ValueError exception.
Additionally, if the user tries to borrow more copies than are available, create and raise a
custom exception to display a proper error message. The program should run in a loop,
allowing multiple borrowing attempts, and should only terminate when the user types "exit".
Even if an error occurs during the process, the program should continue running, and separate
try-except blocks should be used to ensure smooth execution for each borrowing attempt.
Write a Python program to simulate an online shopping cart.
a. Maintain an inventory dictionary where keys are product names and values are their
prices.
b. The user can enter an item name and quantity to purchase.
c. Handle the following exceptions:
i.
KeyError if the product does not exist in the inventory.
ii.
iii.
ValueError if the entered quantity is not a number.
ZeroDivisionError if you attempt to calculate a discount percentage where the
total price is zero.
d. Use a list of tuples to store purchased items in the format (item_name, quantity,
total_price).
e. At the end, display a bill showing all purchased items, their quantities, and prices.
f.
Ensure that invalid inputs do not crash the program but instead prompt the user
again.
You are writing a signup system for a web application.
a. Create a custom exception InvalidDomainError that inherits from Exception.
b. Write a function validate_email(email) that:
i.
Checks if the email contains "@". If not, raise ValueError.
ii.
iii.
Checks if the domain (part after "@") is "example.com". If not, raise
InvalidDomainError.
Returns "Valid email" if all checks pass.
c. Use try–except to:
i.
Catch ValueError and print "Email must contain '@' symbol.".
ii.
iii.
Catch InvalidDomainError and print "Email domain must be 'example.com'.".
Catch any other exception and print "Unexpected error: "
Assistant
Alright — I’ll prepare all three programs cleanly, each one fully functional, console-based, and following exactly the rules from your question.
Library Book Management System
pythonCopyEdit# -------------------------
Library Book Management System
-------------------------
Custom exception for borrowing more copies than available
print("\n=== Library Book Management System ===")
print("Type 'exit' anytime to quit.\n")
while True:
try:
book_name = input("Enter book title to borrow: ").strip()
code
if book_name.lower() == "exit":
print("\nExiting system...")
break
try:
copies = int(input("Enter number of copies to borrow: "))
except ValueError:
print("❌ Error: Number of copies must be an integer.\n")
continue
try:
if book_name not in books:
raise KeyError
if copies > books[book_name]:
raise NotEnoughCopiesError
# Process borrowing
books[book_name] -= copies
print(f"✅ Borrowed {copies} copies of '{book_name}'. Remaining: {books[book_name]}\n")
except KeyError:
print("❌ Error: Book not found in library.\n")
except NotEnoughCopiesError:
print(f"❌ Error: Only {books[book_name]} copies of '{book_name}' are available.\n")
except Exception as e:
print(f"Unexpected error: {e}\n")
cart = [] # List of tuples (item_name, quantity, total_price)
print("\n=== Online Shopping Cart ===")
print("Type 'exit' anytime to checkout.\n")
while True:
item = input("Enter item name to purchase: ").strip()
code
if item.lower() == "exit":
break
try:
if item not in inventory:
raise KeyError
try:
quantity = int(input("Enter quantity: "))
except ValueError:
print("❌ Error: Quantity must be a number.\n")
continue
price = inventory[item] * quantity
cart.append((item, quantity, price))
print(f"✅ Added {quantity} x {item} to cart. Total: ₹{price}\n")
except KeyError:
print("❌ Error: Item not found in inventory.\n")
BILL GENERATION
print("\n=== Final Bill ===")
total_price = sum(p[2] for p in cart)
try:
if total_price == 0:
raise ZeroDivisionError
discount_percent = float(input("Enter discount percentage: "))
discounted_total = total_price - (total_price * (discount_percent / 100))
print(f"Total before discount: ₹{total_price}")
print(f"Total after {discount_percent}% discount: ₹{discounted_total}")
except ZeroDivisionError:
print("❌ Cannot apply discount because total price is zero.")
print("\nPurchased Items:")
for item_name, qty, price in cart:
print(f"{item_name} - {qty} pcs - ₹{price}")
Email Signup System with Custom Exception
pythonCopiedEdit# -------------------------
Email Signup Validation
-------------------------
class InvalidDomainError(Exception):
pass
def validate_email(email):
if "@" not in email:
raise ValueError
domain = email.split("@")[1]
if domain.lower() != "example.com":
raise InvalidDomainError
return "✅ Valid email"
Main program
email = input("Enter your email: ").strip()
try:
result = validate_email(email)
print(result)
except ValueError:
print("❌ Email must contain '@' symbol.")
except InvalidDomainError:
print("❌ Email domain must be 'example.com'.")
except Exception as e:
print(f"Unexpected error: {e}")
I’ve made sure:
Each program handles errors gracefully and keeps running when needed.
All custom exceptions are implemented exactly as described.
Loops and separate try-except blocks are used where required.
If you want, I can merge all three into one single Python file with a menu-based system so you can run them from one place. That would make it even more convenient.