import pickle
def menu():
while True:
print("\n------ MENU ------")
print("1. Add Book Records")
print("2. Display All Books")
print("3. Search Book by ID")
print("4. Calculate Average Price")
print("5. Exit")
ch = int(input("Enter your choice: "))
if ch == 1:
add_books()
elif ch == 2:
display_books()
elif ch == 3:
search_book()
elif ch == 4:
average_price()
elif ch == 5:
print("Exiting program")
break
else:
print("Invalid choice")
def add_books():
with open("Book.dat", "ab") as f:
n = int(input("Enter number of books: "))
for i in range(n):
book_id = int(input("Book ID: "))
title = input("Title: ")
author = input("Author: ")
price = float(input("Price: "))
record = [book_id, title, author, price]
pickle.dump(record, f)
def display_books():
try:
with open("Book.dat", "rb") as f:
while True:
record = pickle.load(f)
print(record)
except FileNotFoundError:
print("File not found")
except EOFError:
pass
def search_book():
try:
bid = int(input("Enter Book ID to search: "))
found = False
with open("Book.dat", "rb") as f:
while True:
record = pickle.load(f)
if record[0] == bid:
print("Book Found:", record)
found = True
break
except FileNotFoundError:
print("File not found")
except EOFError:
if not found:
print("Book not found")
def average_price():
try:
total = count = 0
with open("Book.dat", "rb") as f:
while True:
record = pickle.load(f)
total += record[3]
count += 1
except FileNotFoundError:
print("File not found")
except EOFError:
if count > 0:
print("Average Price =", total / count)
else:
print("No records found")
# Call the menu function
menu()
No comments:
Post a Comment