-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlibraryFunctions.py
More file actions
160 lines (129 loc) · 5.01 KB
/
libraryFunctions.py
File metadata and controls
160 lines (129 loc) · 5.01 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
import json
with open('library.json', 'r', encoding='utf-8') as file:
books = json.load(file)
precio = 0
def clearScreen():
print("\n" * 15)
def searchTitle(title):
found = False
#Accediendo a los valores de los libros
for book in books.values():
#Verifica algun titulo similar ignorando si hay diferencia de mayusculas o minusculas
if book.get('titulo', '').lower().strip() == title.lower().strip():
found = True
precio = book.get("alquiler")
#Verificar que sea un diccionario
if isinstance(book, dict):
#Mostrar el diccionario de forma elegante
for key, value in book.items():
print(f"{key.capitalize()}: {value}")
#Separador por si encuentra varios resultados similares
print("-" * 15)
return precio
if not found:
print(f"No se encontró ningún libro con el título: {title}\n")
#Si no encuentra nada similar
return None
def searchAuthor(author):
found = False
#Accediendo a los valores de los libros
for book in books.values():
if book.get('autor', '').lower().strip() == author.lower().strip(): # Verifica algun titulo similar ignorando si hay diferencia de mayusculas o minusculas
found = True
if isinstance(book, dict): # Verificar que sea un diccionario
for key, value in book.items():
print(f"{key.capitalize()}: {value}") # Mostrar el diccionario de forma elegante
print("-" * 15) # Separador por si encuentra varios resultados similares
if not found:
print(f"No se encontró ningún libro con el autor: {author}\n")
#Si no encuentra nada similar
def isDeveloping():
clearScreen()
print("Lo siento pero esta funcion esta actualmente en desarrollo\n")
"""def createBook():
title = input("Nombre: \n")
author = input("Autor: \n")
year = int(input("Año de Creacion: \n"))
genere = input("Genero: \n")
rating = int(input("Rating: \n"))
rent = int(input("Precio de renta: \n"))
with open("library.json", "r") as file:
books = json.load(file)
for book in books.values():
number = len(file)
number = {
"titulo": f"{title}",
"autor": f"{author}",
"año": year,
"genero": f"{genere}",
"rating": rating,
"alquiler": rent
}
"""
def rent(title):
precio = searchTitle(title) # Obtenemos el precio desde searchTitle()
if precio is not None: # Si el libro existe
confirmar = input(f"¿Confirmar alquiler? Costo: {precio}$: ").strip().lower()
if confirmar in ("si", "s"):
print(f"¡Libro alquilado por {precio}$!\n")
else:
print("\nAlquiler cancelado.\n\n")
def createBook():
clearScreen()
print("----- Crear Nuevo Libro -----")
# Obtener el nuevo ID (máximo ID existente + 1)
new_id = str(max(int(k) for k in books.keys()) + 1)
# Solicitar datos del libro
title = input("Título: ").strip()
author = input("Autor: ").strip()
# Validar año
while True:
try:
year = int(input("Año de publicación: ").strip())
if year < 0 or year > 2023: # Ajustar según necesidad
print("Por favor ingrese un año válido.")
continue
break
except ValueError:
print("Por favor ingrese un número válido para el año.")
genre = input("Género: ").strip()
# Validar rating
while True:
try:
rating = float(input("Rating (0.0 - 5.0): ").strip())
if rating < 0 or rating > 5:
print("El rating debe estar entre 0.0 y 5.0")
continue
break
except ValueError:
print("Por favor ingrese un número válido para el rating.")
# Validar precio de alquiler
while True:
try:
rent_price = float(input("Precio de alquiler: ").strip())
if rent_price <= 0:
print("El precio debe ser mayor que 0")
continue
break
except ValueError:
print("Por favor ingrese un número válido para el precio.")
# Crear el nuevo libro
new_book = {
"titulo": title,
"autor": author,
"año": year,
"genero": genre,
"rating": rating,
"alquiler": rent_price
}
# Añadir al diccionario de libros
books[new_id] = new_book
# Guardar en el archivo JSON
try:
with open('library.json', 'w', encoding='utf-8') as file:
json.dump(books, file, ensure_ascii=False, indent=4)
print("\n¡Libro creado exitosamente!")
except Exception as e:
print(f"\nError al guardar el libro: {e}")
input("\nPresione Enter para continuar...")
clearScreen()