-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathbook_app.py
More file actions
106 lines (74 loc) · 2.2 KB
/
book_app.py
File metadata and controls
106 lines (74 loc) · 2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import sys
from books import BookCollection
# Global collection instance
collection = BookCollection()
def show_books(books: list) -> None:
"""Display books in a user-friendly format."""
if not books:
print("No books found.")
return
print("\nYour Book Collection:\n")
for index, book in enumerate(books, start=1):
status = "✓" if book.read else " "
print(f"{index}. [{status}] {book.title} by {book.author} ({book.year})")
print()
def handle_list() -> None:
books = collection.list_books()
show_books(books)
def handle_add() -> None:
print("\nAdd a New Book\n")
title = input("Title: ").strip()
if not title:
print("\nError: Title cannot be empty.\n")
return
author = input("Author: ").strip()
if not author:
print("\nError: Author cannot be empty.\n")
return
year_str = input("Year: ").strip()
try:
year = int(year_str) if year_str else 0
collection.add_book(title, author, year)
print("\nBook added successfully.\n")
except ValueError as e:
print(f"\nError: {e}\n")
def handle_remove() -> None:
print("\nRemove a Book\n")
title = input("Enter the title of the book to remove: ").strip()
collection.remove_book(title)
print("\nBook removed if it existed.\n")
def handle_find() -> None:
print("\nFind Books by Author\n")
author = input("Author name: ").strip()
books = collection.find_by_author(author)
show_books(books)
def show_help() -> None:
print("""
Book Collection Helper
Commands:
list - Show all books
add - Add a new book
remove - Remove a book by title
find - Find books by author
help - Show this help message
""")
def main() -> None:
if len(sys.argv) < 2:
show_help()
return
command = sys.argv[1].lower()
if command == "list":
handle_list()
elif command == "add":
handle_add()
elif command == "remove":
handle_remove()
elif command == "find":
handle_find()
elif command == "help":
show_help()
else:
print("Unknown command.\n")
show_help()
if __name__ == "__main__":
main()