Skip to content

Commit 6a7232a

Browse files
authored
Merge pull request mouredev#7648 from victorfer69/main
#10 - Python
2 parents 89408a6 + 0dfec8b commit 6a7232a

File tree

5 files changed

+391
-0
lines changed

5 files changed

+391
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#Excepciones y errores
2+
3+
try:
4+
print(10/1)
5+
6+
my_list = [1,2,3,4]
7+
print(my_list[4])
8+
9+
except Exception as e:
10+
print(f"ERROR: {e}")
11+
12+
print("Hola a todos")
13+
14+
15+
#EJERCICIO EXTRA
16+
17+
class StrTypeError(Exception):
18+
pass
19+
20+
def extra(param:list):
21+
22+
if len(param) < 3:
23+
raise IndexError()
24+
elif param[1] == 0:
25+
raise ZeroDivisionError()
26+
elif type(param[2]) != str:
27+
raise StrTypeError("El tercer elemento debe de ser una cadena de texto")
28+
29+
print(param[2])
30+
print(param[0]/param[1])
31+
32+
33+
try:
34+
extra([1,2,"Hola"])
35+
except IndexError as e:
36+
print("ERROR: el numero de elementos de la lista debe ser mayor de 2")
37+
except ZeroDivisionError as e:
38+
print("ERROR: el segundo elemento de la lista no puede ser cero")
39+
except StrTypeError as e:
40+
print(f"ERROR: {e}")
41+
except Exception as e:
42+
print(f"ERROR inesperado: {e}")
43+
finally:
44+
print("FIN")
Lines changed: 152 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
import os
2+
3+
#EJERCICIO
4+
5+
file_name = "victorfer69.txt"
6+
7+
#Escribir en el fichero
8+
with open(file_name, "w") as file:
9+
file.write("Victor\n")
10+
file.write("21\n")
11+
file.write("Python")
12+
13+
#Leer el fichero
14+
with open(file_name, "r") as file:
15+
print(file.read())
16+
17+
#Borrar el fichero
18+
os.remove(file_name)
19+
20+
21+
#EJERCICIO EXTRA
22+
23+
def gestionDeVentas(file_name:str):
24+
25+
salir = False
26+
27+
while not salir:
28+
29+
print("1. Añadir producto")
30+
print("2. Consultar producto")
31+
print("3. Actualizar producto")
32+
print("4. Borrar producto")
33+
print("5. Mostrar productos")
34+
print("6. Calcular venta total")
35+
print("7. Calcular venta por producto")
36+
print("8. Salir")
37+
action = input("Seleccione el modo:")
38+
39+
match action:
40+
41+
case "1":
42+
43+
name = input("Dame el nombre del producto: ")
44+
quantity = int(input("Dame la cantidad: "))
45+
price = float(input("Dame el precio: "))
46+
47+
with open(file_name, "a") as file:
48+
if name != None and quantity != None and quantity > 0 and price != None and price > 0:
49+
file.write(f"{name}, {quantity}, {price}\n")
50+
else:
51+
print("Algún argumento invalido")
52+
53+
case "2":
54+
55+
product = input("¿Que producto quieres consultar?: ")
56+
existe = False
57+
58+
with open(file_name, "r") as file:
59+
for line in file.readline():
60+
if line.split(",")[0] == product:
61+
print(line)
62+
existe = True
63+
64+
if not existe:
65+
print(f"No hay {product}")
66+
67+
case "3":
68+
69+
name = input("Dame el nombre del producto: ")
70+
quantity = int(input("Dame la cantidad: "))
71+
price = float(input("Dame el precio: "))
72+
73+
with open(file_name, "r") as file:
74+
lines = file.readlines()
75+
76+
with open(file_name, "w") as file:
77+
for line in lines:
78+
if line.split(", ")[0] == name:
79+
file.write(f"{name}, {quantity}, {price}\n")
80+
else:
81+
file.write(line)
82+
83+
case "4":
84+
85+
name = input("Dame el nombre del producto: ")
86+
87+
with open(file_name, "r") as file:
88+
lines = file.readlines()
89+
90+
with open(file_name, "w") as file:
91+
for line in lines:
92+
if line.split(", ")[0] != name:
93+
file.write(line)
94+
95+
case "5":
96+
97+
with open(file_name, "r") as file:
98+
print(file.read())
99+
100+
case "6":
101+
102+
total = 0
103+
104+
with open(file_name, "r") as file:
105+
for line in file.readlines():
106+
components = line.split(", ")
107+
quantity = int(components[1])
108+
price = float(components[2])
109+
total += quantity * price
110+
111+
print(total)
112+
113+
case "7":
114+
115+
name = input("Nombre: ")
116+
total = 0
117+
existe = False
118+
119+
with open(file_name, "r") as file:
120+
for line in file.readlines():
121+
components = line.split(", ")
122+
if components[0] == name:
123+
quantity = int(components[1])
124+
price = float(components[2])
125+
total += quantity * price
126+
existe = True
127+
break
128+
129+
if existe:
130+
print(total)
131+
else:
132+
print(f"El producto {name} no existe")
133+
134+
case "8":
135+
136+
print("Saliendo del programa (borrando fichero)")
137+
os.remove(file_name)
138+
salir = True
139+
140+
case _:
141+
142+
print("Seleccione una opcion correcta.")
143+
144+
145+
#Fichero inicial
146+
with open("ventas.txt", "a") as file:
147+
file.write("Patata, 4, 0.25\n")
148+
file.write("Pan, 5, 0.2\n")
149+
file.write("Sopa, 2, 0.5\n")
150+
file.write("Carne, 1, 1\n")
151+
152+
gestionDeVentas("ventas.txt")
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
import os
2+
import xml.etree.ElementTree as xml
3+
import json
4+
5+
#EJERCICIO
6+
7+
data = {
8+
"name" : "Victor",
9+
"age" : 21,
10+
"birthday" : "06-09-2003",
11+
"languages" : ["Python", "Java", "Swift"]
12+
}
13+
14+
xml_file = "victorfer69.xml"
15+
json_file = "victorfer69.json"
16+
17+
18+
#XML
19+
def save_xml():
20+
21+
root = xml.Element("data")
22+
23+
for key, value in data.items():
24+
child = xml.SubElement(root, key)
25+
if isinstance(value, list):
26+
for item in value:
27+
child2 = xml.SubElement(child, "item").text = item
28+
else:
29+
child.text = str(value)
30+
31+
tree = xml.ElementTree(root)
32+
tree.write(xml_file)
33+
34+
save_xml()
35+
36+
with open(xml_file, "r") as xml_data:
37+
print (xml_data.read())
38+
39+
os.remove(xml_file)
40+
41+
42+
#JSON
43+
def save_json():
44+
with open(json_file, "w") as json_data:
45+
json.dump(data, json_data)
46+
47+
save_json()
48+
49+
with open(json_file, "r") as json_data:
50+
print(json_data.read())
51+
52+
os.remove(json_file)
53+
54+
55+
#EJERCICIO EXTRA
56+
57+
save_xml()
58+
save_json()
59+
60+
class Data:
61+
62+
def __init__(self, name, age, birthday, languages):
63+
self.name = name
64+
self.age = age
65+
self.birthday = birthday
66+
self.languages = languages
67+
68+
69+
with open(xml_file, "r") as xml_data:
70+
71+
root = xml.fromstring(xml_data.read())
72+
name = root.find("name").text
73+
age = root.find("age").text
74+
birth_date = root.find("birthday").text
75+
programming_languages = []
76+
for item in root.find("languages"):
77+
programming_languages.append(item.text)
78+
79+
xml_class = Data(name, age, birth_date, programming_languages)
80+
print(f"XML: {xml_class.__dict__}")
81+
82+
83+
with open(json_file, "r") as json_data:
84+
json_dict = json.load(json_data)
85+
json_class = Data(
86+
json_dict["name"],
87+
json_dict["age"],
88+
json_dict["birthday"],
89+
json_dict["languages"]
90+
)
91+
print(f"JSON: {json_class.__dict__}")
92+
93+
os.remove(xml_file)
94+
os.remove(json_file)
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import unittest
2+
from datetime import datetime, date
3+
4+
"""
5+
Ejercicio
6+
"""
7+
8+
9+
def sum(a, b):
10+
if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
11+
return ValueError("Los argumentos deben de ser enteros o decimales.")
12+
return a + b
13+
14+
15+
class TestSum(unittest.TestCase):
16+
17+
def test_sum(self):
18+
self.assertEqual(sum(5, 7), 12)
19+
self.assertEqual(sum(5, -7), -2)
20+
self.assertEqual(sum(0, 0), 0)
21+
self.assertEqual(sum(5.1, 7.1), 12.2)
22+
23+
def test_sum_type(self):
24+
with self.assertRaises(ValueError):
25+
sum("5", 7)
26+
with self.assertRaises(ValueError):
27+
sum(5, "7")
28+
with self.assertRaises(ValueError):
29+
sum("5", "7")
30+
31+
32+
#EJERCIICO EXTRA
33+
dicc = {
34+
"name": "Victor",
35+
"age": 21,
36+
"birth_date": "06-09-2003",
37+
"programming_languages": ["Python", "Java", "C"]
38+
}
39+
40+
class TestSum(unittest.TestCase):
41+
42+
def test_all_param(self):
43+
self.assertIn("name", dicc)
44+
self.assertIn("age", dicc)
45+
self.assertIn("birth_date", dicc)
46+
self.assertIn("programming_languages", dicc)
47+
48+
def test_correct_data(self):
49+
self.assertIsInstance(dicc["name"], str)
50+
self.assertIsInstance(dicc["age"], int)
51+
self.assertIsInstance(dicc["birth_date"], str)
52+
self.assertIsInstance(dicc["programming_languages"], list)
53+
54+
unittest.main()

0 commit comments

Comments
 (0)