Skip to content

Commit 95de7c6

Browse files
authored
Merge pull request #3134 from nlarrea/py-reto11
#11 - python
2 parents cb54473 + 6d87abd commit 95de7c6

File tree

1 file changed

+229
-0
lines changed

1 file changed

+229
-0
lines changed
Lines changed: 229 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,229 @@
1+
"""
2+
* IMPORTANTE: Sólo debes subir el fichero de código como parte del ejercicio.
3+
*
4+
* EJERCICIO:
5+
* Desarrolla un programa capaz de crear un archivo que se llame como
6+
* tu usuario de GitHub y tenga la extensión .txt.
7+
* Añade varias líneas en ese fichero:
8+
* - Tu nombre.
9+
* - Edad.
10+
* - Lenguaje de programación favorito.
11+
* Imprime el contenido.
12+
* Borra el fichero.
13+
*
14+
* DIFICULTAD EXTRA (opcional):
15+
* Desarrolla un programa de gestión de ventas que almacena sus datos en un
16+
* archivo .txt.
17+
* - Cada producto se guarda en una línea del archivo de la siguiente manera:
18+
* [nombre_producto], [cantidad_vendida], [precio].
19+
* - Siguiendo ese formato, y mediante terminal, debe permitir añadir, consultar,
20+
* actualizar, eliminar productos y salir.
21+
* - También debe poseer opciones para calcular la venta total y por producto.
22+
* - La opción salir borra el .txt.
23+
"""
24+
25+
file_path = "nlarrea.txt"
26+
27+
# Write data to the file
28+
with open(file_path, "w") as f:
29+
f.write("Naia\n")
30+
f.write("25\n")
31+
f.write("Python\n")
32+
33+
# Read the file and print the content
34+
# OPTION 1: Read all the content
35+
print("Print file - Option 1:")
36+
with open(file_path, "r") as f:
37+
print(f.read())
38+
39+
# OPTION 2: Read line by line
40+
print("Print file - Option 2:")
41+
with open(file_path, "r") as f:
42+
for line in f.readlines():
43+
print(line.strip())
44+
45+
# Remove the file
46+
import os
47+
48+
os.remove(file_path)
49+
50+
51+
"""
52+
* DIFICULTAD EXTRA (opcional):
53+
* Desarrolla un programa de gestión de ventas que almacena sus datos en un
54+
* archivo .txt.
55+
* - Cada producto se guarda en una línea del archivo de la siguiente manera:
56+
* [nombre_producto], [cantidad_vendida], [precio].
57+
* - Siguiendo ese formato, y mediante terminal, debe permitir añadir, consultar,
58+
* actualizar, eliminar productos y salir.
59+
* - También debe poseer opciones para calcular la venta total y por producto.
60+
* - La opción salir borra el .txt.
61+
"""
62+
63+
64+
file_path = "sales.txt"
65+
66+
67+
def ask_option(options: tuple) -> int:
68+
print("\nMENU")
69+
for index, option in enumerate(options):
70+
print(f"{index}. {option}")
71+
72+
while True:
73+
try:
74+
chosen_option = input("What do you want to do?\n> ")
75+
if not chosen_option.isnumeric():
76+
raise TypeError(f"Chosen option must be a number!")
77+
elif int(chosen_option) < 0 or int(chosen_option) >= len(options):
78+
raise ValueError(
79+
f"Chosen option must be a number between {0}-{len(options) - 1}!"
80+
)
81+
except Exception as error:
82+
print(error)
83+
else:
84+
return int(chosen_option)
85+
86+
87+
def run():
88+
while True:
89+
options: tuple = (
90+
"Exit",
91+
"Add products",
92+
"See single product",
93+
"See all products",
94+
"Update products",
95+
"Remove products",
96+
"Calculate total sales",
97+
"Calculate sales by product",
98+
)
99+
option = ask_option(options)
100+
print("\nChosen option:", options[int(option)], "\n")
101+
102+
if option == 0:
103+
try:
104+
os.remove(file_path)
105+
except FileNotFoundError:
106+
# If there is no file yet -> nothing happens
107+
pass
108+
109+
return
110+
111+
try:
112+
if option == 1:
113+
# ADD PRODUCTS
114+
try:
115+
product = input("Product name:\n > ")
116+
117+
amount_sold = input("Amount sold:\n > ")
118+
if not amount_sold.replace(".", "", 1).isnumeric():
119+
raise TypeError("Amount must be a number!")
120+
121+
price = input("Price:\n > ")
122+
if not price.replace(".", "", 1).isnumeric():
123+
raise TypeError("Price must be a number!")
124+
125+
except Exception as error:
126+
print(f"{type(error).__name__}: {error}")
127+
128+
else:
129+
with open(file_path, "a") as f:
130+
f.write(f"{product}, {amount_sold}, {price}\n")
131+
132+
elif option == 2:
133+
# SEE SINGLE PRODUCT
134+
product = input("Product name:\n > ")
135+
136+
with open(file_path, "r") as f:
137+
for line in f.readlines():
138+
if line.split(", ")[0] == product:
139+
print("\n", line)
140+
141+
elif option == 3:
142+
# SEE ALL PRODUCTS
143+
with open(file_path, "r") as f:
144+
print("\n", f.read())
145+
146+
elif option == 4:
147+
# UPDATE PRODUCT
148+
try:
149+
product = input("Product name:\n > ")
150+
151+
amount_sold = input("New amount sold:\n > ")
152+
if not amount_sold.replace(".", "", 1).isnumeric():
153+
raise TypeError("Amount must be a number!")
154+
155+
price = input("New price:\n > ")
156+
if not price.replace(".", "", 1).isnumeric():
157+
raise TypeError("Price must be a number!")
158+
159+
except Exception as error:
160+
print(f"{type(error).__name__}: {error}")
161+
162+
else:
163+
# Read current data
164+
with open(file_path, "r") as f:
165+
lines = f.readlines()
166+
167+
# Write old and new data
168+
with open(file_path, "w") as f:
169+
for line in lines:
170+
if (
171+
line.split(", ")[0].strip().lower()
172+
== product.strip().lower()
173+
):
174+
f.write(f"{product}, {amount_sold}, {price}\n")
175+
else:
176+
f.write(line)
177+
178+
elif option == 5:
179+
# REMOVE PRODUCT
180+
product = input("Product name:\n > ")
181+
182+
with open(file_path, "r") as f:
183+
lines = f.readlines()
184+
185+
with open(file_path, "w") as f:
186+
for line in lines:
187+
if (
188+
line.split(", ")[0].strip().lower()
189+
!= product.strip().lower()
190+
):
191+
f.write(line)
192+
193+
elif option == 6:
194+
# CALCULATE TOTAL SALES
195+
with open(file_path, "r") as f:
196+
lines = f.readlines()
197+
198+
sales = 0
199+
for line in lines:
200+
amount_sold = int(line.split(", ")[1].strip())
201+
price = float(line.split(", ")[2].strip())
202+
sales += amount_sold * price
203+
204+
print("Total sales:", sales)
205+
206+
elif option == 7:
207+
# CALCULATE SINGLE PRODUCT'S SALES
208+
product = input("Product name:\n > ")
209+
210+
with open(file_path, "r") as f:
211+
lines = f.readlines()
212+
213+
for line in lines:
214+
components = line.split(", ")
215+
if components[0] == product:
216+
amount_sold = int(components[1].strip())
217+
price = float(components[2].strip())
218+
sales = amount_sold * price
219+
220+
print("Product sales:", sales)
221+
break
222+
else:
223+
print(f"No '{product}' product has been found.")
224+
225+
except FileNotFoundError:
226+
print("There is no product data yet.")
227+
228+
229+
run()

0 commit comments

Comments
 (0)