From d8739fdc35d5068da2bdf0ac253cd42c223298d8 Mon Sep 17 00:00:00 2001 From: miguel-angel-git Date: Wed, 29 Oct 2025 13:45:23 +0100 Subject: [PATCH 1/3] =?UTF-8?q?feat:=20completar=20calculadora=20v3=20-=20?= =?UTF-8?q?men=C3=BA=20interactivo=20con=20validaci=C3=B3n?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ejercicio_guiado/calculadora_v3.py | 68 +++++++++---------- 1 file changed, 33 insertions(+), 35 deletions(-) diff --git a/03_control_flujo/ejercicio_guiado/calculadora_v3.py b/03_control_flujo/ejercicio_guiado/calculadora_v3.py index 02191bc..7a7cfa6 100644 --- a/03_control_flujo/ejercicio_guiado/calculadora_v3.py +++ b/03_control_flujo/ejercicio_guiado/calculadora_v3.py @@ -22,63 +22,61 @@ """ # TODO 1: Crea el bucle principal -# while True: -# # Todo el código va aquí dentro - - +while True: + # Todo el código va aquí dentro # TODO 2: Muestra el menú - # print("\n=== CALCULADORA ===") - # print("1. Sumar") - # print("2. Restar") - # print("3. Multiplicar") - # print("4. Dividir") - # print("5. Salir") + print("\n=== CALCULADORA ===") + print("1. Sumar") + print("2. Restar") + print("3. Multiplicar") + print("4. Dividir") + print("5. Salir") # TODO 3: Pide la opción al usuario - # opcion = input("\nElige una opción: ") + opcion = input("\nElige una opción: ") # TODO 4: Si elige salir (opción 5), termina el programa - # if opcion == "5": - # print("¡Hasta pronto! 👋") - # break # Sale del bucle while + if opcion == "5": + print("¡Hasta pronto! 👋") + break # Sale del bucle while # TODO 5: Valida que la opción sea válida (1, 2, 3 o 4) - # if opcion not in ["1", "2", "3", "4"]: - # print("❌ Opción no válida. Intenta de nuevo.") - # continue # Vuelve al inicio del bucle (muestra el menú de nuevo) + if opcion not in ["1", "2", "3", "4"]: + print("❌ Opción no válida. Intenta de nuevo.") + continue # Vuelve al inicio del bucle (muestra el menú de nuevo) # TODO 6: Pide los dos números - # num1 = float(input("Primer número: ")) - # num2 = float(input("Segundo número: ")) + num1 = float(input("Primer número: ")) + num2 = float(input("Segundo número: ")) # TODO 7: Controla la división por cero - # if opcion == "4" and num2 == 0: - # print("❌ Error: No se puede dividir por cero") - # continue # Vuelve al menú sin hacer la operación + if opcion == "4" and num2 == 0: + print("❌ Error: No se puede dividir por cero") + continue # Vuelve al menú sin hacer la operación # TODO 8: Realiza la operación según la opción elegida - # if opcion == "1": - # resultado = num1 + num2 - # simbolo = "+" - # elif opcion == "2": - # resultado = num1 - num2 - # simbolo = "-" - # elif opcion == "3": - # resultado = num1 * num2 - # simbolo = "*" - # elif opcion == "4": - # resultado = num1 / num2 - # simbolo = "/" + if opcion == "1": + resultado = num1 + num2 + simbolo = "+" + elif opcion == "2": + resultado = num1 - num2 + simbolo = "-" + elif opcion == "3": + resultado = num1 * num2 + simbolo = "*" + elif opcion == "4": + resultado = num1 / num2 + simbolo = "/" # TODO 9: Muestra el resultado con f-string - # print(f"✅ {num1} {simbolo} {num2} = {resultado:.2f}") + print(f"✅ {num1} {simbolo} {num2} = {resultado:.2f}") # ¡Excelente trabajo! Ahora tienes una calculadora interactiva que: From 76e7b7d2c8ee4fa8b7e21d2087f8a7b4a62b1589 Mon Sep 17 00:00:00 2001 From: miguel-angel-git Date: Wed, 29 Oct 2025 22:20:36 +0100 Subject: [PATCH 2/3] feat: calculadora v5 - historial de operaciones con listas y diccionarios --- .../ejercicio_guiado/calculadora_v5.py | 92 +++++++++---------- 1 file changed, 46 insertions(+), 46 deletions(-) diff --git a/05_colecciones/ejercicio_guiado/calculadora_v5.py b/05_colecciones/ejercicio_guiado/calculadora_v5.py index 3caf649..23568c9 100644 --- a/05_colecciones/ejercicio_guiado/calculadora_v5.py +++ b/05_colecciones/ejercicio_guiado/calculadora_v5.py @@ -65,7 +65,7 @@ def obtener_numeros(): # TODO 1: Crea una lista global para almacenar el historial # (Nota: en programación avanzada evitamos globales, pero aquí es didáctico) -# historial = [] +historial = [] def guardar_operacion(num1, num2, operacion, resultado): @@ -78,34 +78,34 @@ def guardar_operacion(num1, num2, operacion, resultado): resultado: Resultado de la operación """ # TODO 2: Crea un diccionario con los datos de la operación - # operacion_dict = { - # "num1": num1, - # "num2": num2, - # "operacion": operacion, - # "resultado": resultado - # } + operacion_dict = { + "num1": num1, + "num2": num2, + "operacion": operacion, + "resultado": resultado + } # TODO 3: Añade el diccionario a la lista historial - # historial.append(operacion_dict) + historial.append(operacion_dict) - pass + def mostrar_historial(): """Muestra todas las operaciones del historial.""" # TODO 4: Verifica si el historial está vacío - # if not historial: - # print("📭 No hay operaciones en el historial") - # return + if not historial: + print("📭 No hay operaciones en el historial") + return # TODO 5: Muestra el título - # print("\n📜 HISTORIAL DE OPERACIONES:") + print("\n📜 HISTORIAL DE OPERACIONES:") # TODO 6: Itera sobre el historial con enumerate() # enumerate() nos da el índice (i) y el elemento (op) # El segundo parámetro (1) indica que empiece a contar desde 1 - # for i, op in enumerate(historial, 1): - # print(f"{i}. {op['num1']} {op['operacion']} {op['num2']} = {op['resultado']:.2f}") + for i, op in enumerate(historial, 1): + print(f"{i}. {op['num1']} {op['operacion']} {op['num2']} = {op['resultado']:.2f}") pass @@ -115,49 +115,49 @@ def mostrar_historial(): def main(): """Función principal de la calculadora.""" - # while True: - # mostrar_menu() - # opcion = input("\nElige una opción: ") + while True: + mostrar_menu() + opcion = input("\nElige una opción: ") # TODO 7: Actualiza la condición de salir (ahora es la opción 6) - # if opcion == "6": - # print("¡Hasta pronto! 👋") - # break + if opcion == "6": + print("¡Hasta pronto! 👋") + break # TODO 8: Añade la nueva opción 5 para ver el historial - # if opcion == "5": - # mostrar_historial() - # continue # Vuelve al menú sin pedir números + if opcion == "5": + mostrar_historial() + continue # Vuelve al menú sin pedir números # TODO 9: Actualiza la validación (ahora hay 5 opciones válidas) - # if opcion not in ["1", "2", "3", "4", "5"]: - # print("❌ Opción no válida") - # continue + if opcion not in ["1", "2", "3", "4", "5"]: + print("❌ Opción no válida") + continue - # num1, num2 = obtener_numeros() + num1, num2 = obtener_numeros() - # if opcion == "4" and num2 == 0: - # print("❌ No se puede dividir por cero") - # continue + if opcion == "4" and num2 == 0: + print("❌ No se puede dividir por cero") + continue # TODO 10: Realiza la operación y guarda en el historial - # if opcion == "1": - # resultado = sumar(num1, num2) - # simbolo = "+" - # elif opcion == "2": - # resultado = restar(num1, num2) - # simbolo = "-" - # elif opcion == "3": - # resultado = multiplicar(num1, num2) - # simbolo = "*" - # elif opcion == "4": - # resultado = dividir(num1, num2) - # simbolo = "/" - - # print(f"✅ {num1} {simbolo} {num2} = {resultado:.2f}") + if opcion == "1": + resultado = sumar(num1, num2) + simbolo = "+" + elif opcion == "2": + resultado = restar(num1, num2) + simbolo = "-" + elif opcion == "3": + resultado = multiplicar(num1, num2) + simbolo = "*" + elif opcion == "4": + resultado = dividir(num1, num2) + simbolo = "/" + + print(f"✅ {num1} {simbolo} {num2} = {resultado:.2f}") # TODO 11: Guarda la operación en el historial - # guardar_operacion(num1, num2, simbolo, resultado) + guardar_operacion(num1, num2, simbolo, resultado) pass From b6ae64117276ba0a0cffcf6748a2f2ee95997ee0 Mon Sep 17 00:00:00 2001 From: miguel-angel-git Date: Tue, 4 Nov 2025 09:51:08 +0100 Subject: [PATCH 3/3] ejercicios hechos,falta calculadora --- 01_intro/P99_Bigotes_felices.py | 11 ++ 01_intro/ejercicio_guiado/calculadora_v1.py | 11 +- 01_intro/guiado1_saludo_input.py | 3 + 01_intro/guiado2.py | 3 + 01_intro/p1_variables_basicas.py | 4 + 01_intro/p2_conversor.py | 10 ++ 01_intro/p3_tres_prints.py | 5 + 01_intro/p4_eco.py | 3 + .../ejercicio_guiado/calculadora_v2.py | 50 ++++-- .../ejercicio_guiado/operaciones.py | 8 + 02_estructuras/p1_booleans.py | 22 +++ 02_estructuras/p2_strings.py | 12 ++ 02_estructuras/p3_redondeo.py | 3 + 02_estructuras/p4_porcentajes.py | 7 + .../p99_gatos_felices_Media_pesos.py | 10 ++ 03_control_flujo/Autonomos.py | 53 ++++++ .../Guiado1_ClasificadorSimple.py | 16 ++ 03_control_flujo/Guiado2_SumaAcumulada.py | 17 ++ .../ejercicio_guiado/calculadora_v3.py | 17 +- 03_control_flujo/p1_casting.py | 10 ++ .../p1_lista_de_Nombres_de_gatos.py | 4 + 03_control_flujo/p2_contarLetrasString.py | 8 + 03_control_flujo/p3_tablas_multiplicar_5.py | 5 + 03_control_flujo/p4_adivina.py | 11 ++ .../p99_Bigotes_felices_turnos.py | 22 +++ 04_funciones/Guiado1_saludar.py | 7 + 04_funciones/Guiado2_sumar.py | 9 + .../ejercicio_guiado/calculadora_v4.py | 114 +++++++------ 04_funciones/p1_esPar.py | 19 +++ 04_funciones/p2_area_rectangulo.py | 8 + 04_funciones/p3_formatear_gato.py | 10 ++ 04_funciones/p4_promedio.py | 18 ++ 04_funciones/p5_validarEdad.py | 13 ++ 04_funciones/p99_bigotesFelicesEdad.py | 15 ++ 05_colecciones/Guiado1_ListaDeGatos.py | 3 + 05_colecciones/guiado2_DiccionarioSimple.py | 10 ++ 05_colecciones/p1_vacunasSet.py | 6 + 05_colecciones/p2_coleccionesNombreEdad.py | 24 +++ .../p3_concurrencia_string_diccionario.py | 10 ++ 05_colecciones/p4_slicing.py | 7 + 05_colecciones/p5_reporte.py | 9 + .../Guiado1_guardar_3Lineas.py | 17 ++ 06_archivos_y_modulos/Guiado2_leerLineas.py | 8 + .../ejercicio_guiado/calculadora_v6.py | 154 +++++++++--------- 06_archivos_y_modulos/p1_gatosCSV.py | 27 +++ .../p3_leer_guardar_con_utiles.py | 16 ++ 06_archivos_y_modulos/p4_FileNotFoundError.py | 13 ++ 06_archivos_y_modulos/utiles.py | 14 ++ 07_mini_proyectos/p1_EstadisticasGatos.py | 31 ++++ 07_mini_proyectos/p1_funciones.py | 45 +++++ 07_mini_proyectos/tickets.py | 27 +++ datos.txt | 3 + escribir.txt | 3 + gatos.json | 5 + gatos.txt | 1 + 55 files changed, 823 insertions(+), 148 deletions(-) create mode 100644 01_intro/P99_Bigotes_felices.py create mode 100644 01_intro/guiado1_saludo_input.py create mode 100644 01_intro/guiado2.py create mode 100644 01_intro/p1_variables_basicas.py create mode 100644 01_intro/p2_conversor.py create mode 100644 01_intro/p3_tres_prints.py create mode 100644 01_intro/p4_eco.py create mode 100644 02_estructuras/ejercicio_guiado/operaciones.py create mode 100644 02_estructuras/p1_booleans.py create mode 100644 02_estructuras/p2_strings.py create mode 100644 02_estructuras/p3_redondeo.py create mode 100644 02_estructuras/p4_porcentajes.py create mode 100644 02_estructuras/p99_gatos_felices_Media_pesos.py create mode 100644 03_control_flujo/Autonomos.py create mode 100644 03_control_flujo/Guiado1_ClasificadorSimple.py create mode 100644 03_control_flujo/Guiado2_SumaAcumulada.py create mode 100644 03_control_flujo/p1_casting.py create mode 100644 03_control_flujo/p1_lista_de_Nombres_de_gatos.py create mode 100644 03_control_flujo/p2_contarLetrasString.py create mode 100644 03_control_flujo/p3_tablas_multiplicar_5.py create mode 100644 03_control_flujo/p4_adivina.py create mode 100644 03_control_flujo/p99_Bigotes_felices_turnos.py create mode 100644 04_funciones/Guiado1_saludar.py create mode 100644 04_funciones/Guiado2_sumar.py create mode 100644 04_funciones/p1_esPar.py create mode 100644 04_funciones/p2_area_rectangulo.py create mode 100644 04_funciones/p3_formatear_gato.py create mode 100644 04_funciones/p4_promedio.py create mode 100644 04_funciones/p5_validarEdad.py create mode 100644 04_funciones/p99_bigotesFelicesEdad.py create mode 100644 05_colecciones/Guiado1_ListaDeGatos.py create mode 100644 05_colecciones/guiado2_DiccionarioSimple.py create mode 100644 05_colecciones/p1_vacunasSet.py create mode 100644 05_colecciones/p2_coleccionesNombreEdad.py create mode 100644 05_colecciones/p3_concurrencia_string_diccionario.py create mode 100644 05_colecciones/p4_slicing.py create mode 100644 05_colecciones/p5_reporte.py create mode 100644 06_archivos_y_modulos/Guiado1_guardar_3Lineas.py create mode 100644 06_archivos_y_modulos/Guiado2_leerLineas.py create mode 100644 06_archivos_y_modulos/p1_gatosCSV.py create mode 100644 06_archivos_y_modulos/p3_leer_guardar_con_utiles.py create mode 100644 06_archivos_y_modulos/p4_FileNotFoundError.py create mode 100644 06_archivos_y_modulos/utiles.py create mode 100644 07_mini_proyectos/p1_EstadisticasGatos.py create mode 100644 07_mini_proyectos/p1_funciones.py create mode 100644 07_mini_proyectos/tickets.py create mode 100644 datos.txt create mode 100644 escribir.txt create mode 100644 gatos.json create mode 100644 gatos.txt diff --git a/01_intro/P99_Bigotes_felices.py b/01_intro/P99_Bigotes_felices.py new file mode 100644 index 0000000..3ea2706 --- /dev/null +++ b/01_intro/P99_Bigotes_felices.py @@ -0,0 +1,11 @@ +nombre=input("Como se llama: ") + +edad=input("Edad que tiene: ") + +try: + edad=float(edad) +except ValueError: + print ("--Edad inválida--") + edad="edad desconocida"; + +print(f"Se llama {nombre} y tiene {edad}.") \ No newline at end of file diff --git a/01_intro/ejercicio_guiado/calculadora_v1.py b/01_intro/ejercicio_guiado/calculadora_v1.py index cb19414..0e5d52c 100644 --- a/01_intro/ejercicio_guiado/calculadora_v1.py +++ b/01_intro/ejercicio_guiado/calculadora_v1.py @@ -21,26 +21,31 @@ # TODO 1: Pide el primer número al usuario # Pista: usa input() y guarda el valor en una variable # primer_numero = ... - +print("Dame el primer valor: ") +valor1=input() # TODO 2: Pide el segundo número al usuario # segundo_numero = ... - +print("Dame el segundo valor: ") +valor2=input() # TODO 3: Convierte los strings a números decimales # Pista: usa float() para permitir decimales (ej: 3.5) # num1 = float(primer_numero) # num2 = ... +valor1=float(valor1); +valor2=float(valor2); # TODO 4: Realiza la suma # resultado = ... +suma= valor1+valor2; # TODO 5: Muestra el resultado # Pista: print("El resultado es:", resultado) - +print (suma); # ¡Ya está! Ejecuta el programa y prueba con diferentes números # Ejemplos para probar: # - 5 y 3 → debe dar 8 diff --git a/01_intro/guiado1_saludo_input.py b/01_intro/guiado1_saludo_input.py new file mode 100644 index 0000000..812186e --- /dev/null +++ b/01_intro/guiado1_saludo_input.py @@ -0,0 +1,3 @@ +nombre="Ana" + +print(f"Hola {nombre} "); \ No newline at end of file diff --git a/01_intro/guiado2.py b/01_intro/guiado2.py new file mode 100644 index 0000000..00e310f --- /dev/null +++ b/01_intro/guiado2.py @@ -0,0 +1,3 @@ +nombre=input("Como te llamas: ") + +print( f"Hola {nombre}!!!") \ No newline at end of file diff --git a/01_intro/p1_variables_basicas.py b/01_intro/p1_variables_basicas.py new file mode 100644 index 0000000..607dae8 --- /dev/null +++ b/01_intro/p1_variables_basicas.py @@ -0,0 +1,4 @@ +nombre="Ana" +ciudad="Madrid" + +print(f"\n\t-- {nombre} vive en {ciudad} --\n"); \ No newline at end of file diff --git a/01_intro/p2_conversor.py b/01_intro/p2_conversor.py new file mode 100644 index 0000000..9df61e7 --- /dev/null +++ b/01_intro/p2_conversor.py @@ -0,0 +1,10 @@ + +numero=input("dame un numero: "); + +try: + numero=float(numero); +except ValueError: + print("Error de conversor") + + +print (f"El valor es: {numero}") \ No newline at end of file diff --git a/01_intro/p3_tres_prints.py b/01_intro/p3_tres_prints.py new file mode 100644 index 0000000..54a3dc8 --- /dev/null +++ b/01_intro/p3_tres_prints.py @@ -0,0 +1,5 @@ +nombre="Ana" +ciudad="Madrid" +edad=27 + +print( f"\n Se llama {nombre}, vive en {ciudad} y tiene {edad} años\n") \ No newline at end of file diff --git a/01_intro/p4_eco.py b/01_intro/p4_eco.py new file mode 100644 index 0000000..4813480 --- /dev/null +++ b/01_intro/p4_eco.py @@ -0,0 +1,3 @@ +echo=input("habla: ") + +print((echo + " ") *3) \ No newline at end of file diff --git a/02_estructuras/ejercicio_guiado/calculadora_v2.py b/02_estructuras/ejercicio_guiado/calculadora_v2.py index 424d58f..646a286 100644 --- a/02_estructuras/ejercicio_guiado/calculadora_v2.py +++ b/02_estructuras/ejercicio_guiado/calculadora_v2.py @@ -20,37 +20,61 @@ # TODO 1: Pide el primer número al usuario y conviértelo a float # num1 = ... - +try: + num1=float(input("Dame una variable: ")); # TODO 2: Pide el segundo número al usuario y conviértelo a float # num2 = ... - + num2=float(input("Dame otra: ")); # TODO 3: Pregunta qué operación desea realizar # Pista: input("¿Qué operación deseas realizar? (+, -, *, /): ") # operacion = ... + print ("Que operacion quieres hacer: ") + + operacion =input() +except: + print ("Valores no aceptados") + num1=0 + num2=0 + operacion=0 # TODO 4: Realiza la operación correspondiente usando if/elif/else # Pista: Compara la variable 'operacion' con "+", "-", "*", "/" # -# if operacion == "+": -# resultado = num1 + num2 -# elif operacion == "-": -# ... -# elif operacion == "*": -# ... -# elif operacion == "/": -# ... -# else: -# print("❌ Operación no válida") +if operacion == "+": + resultado = num1 + num2 +elif operacion == "-": + ... +elif operacion == "*": + ... +elif operacion == "/": + ... +else: + print("❌ Operación no válida") + + +if operacion == "+": + resultado = num1 + num2 +elif operacion == "-": + resultado = num1 - num2 +elif operacion == "*": + resultado = num1 * num2 +elif operacion == "/": + resultado = round(num1 / num2,2) +else: + print("❌ Operación no válida"); + resultado="Operacion no realizada" + # TODO 5: Muestra el resultado usando f-strings # Pista: f"El resultado de {num1} {operacion} {num2} = {resultado:.2f}" # El :.2f muestra solo 2 decimales -# print(f"...") +print(f"...") +print(f"el resutado es: {resultado}") # ¡Perfecto! Ahora tu calculadora puede hacer las 4 operaciones básicas # diff --git a/02_estructuras/ejercicio_guiado/operaciones.py b/02_estructuras/ejercicio_guiado/operaciones.py new file mode 100644 index 0000000..d162a6b --- /dev/null +++ b/02_estructuras/ejercicio_guiado/operaciones.py @@ -0,0 +1,8 @@ +a=10 +b=3 + +print(f"suma: {a+b}") +print(f"resta: {a-3}") + +print(f"Multi: {a*3}") +print(f"div: {round(a/3,2)}") \ No newline at end of file diff --git a/02_estructuras/p1_booleans.py b/02_estructuras/p1_booleans.py new file mode 100644 index 0000000..a385cbf --- /dev/null +++ b/02_estructuras/p1_booleans.py @@ -0,0 +1,22 @@ + +a=10; +aa=10; + +b=5; + + +print (f"es {a} == {aa}: {aa==a}") +print (f"es {a} == {b}: {a==b}") +print (f"es {a} != {b}: {a!=b}") + +print("----") +print (f"es {a} < {b}: {a {b}: {a>b}") + +print("----") +print (f"es {a} <= {a}: {a<=a}") +print (f"es {a} >= {a}: {a>=a}") + +print("----") +print (f"es {a} <= {b}: {a<=b}") +print (f"es {a} >= {b}: {a>=b}") \ No newline at end of file diff --git a/02_estructuras/p2_strings.py b/02_estructuras/p2_strings.py new file mode 100644 index 0000000..90fe089 --- /dev/null +++ b/02_estructuras/p2_strings.py @@ -0,0 +1,12 @@ +def title(nombre, ape): + print(f"el nombre y apellido es {nombre} y {ape}") + + + +print ("dame un nombre:") +nombre=input(); + +print ("dame un Apellido:") +apellido=input(); + +title(nombre, apellido); \ No newline at end of file diff --git a/02_estructuras/p3_redondeo.py b/02_estructuras/p3_redondeo.py new file mode 100644 index 0000000..fe5d3dc --- /dev/null +++ b/02_estructuras/p3_redondeo.py @@ -0,0 +1,3 @@ +import math +print ("redondeo del numero Phi a 3 decimales: ") +print (round(math.pi,3)) diff --git a/02_estructuras/p4_porcentajes.py b/02_estructuras/p4_porcentajes.py new file mode 100644 index 0000000..b620f55 --- /dev/null +++ b/02_estructuras/p4_porcentajes.py @@ -0,0 +1,7 @@ +print ("Dame un numero"); +try: + numero=float(input()) +finally: + print ("conversion fallida"); + +print(f"El 15% de {numero} es {round(numero*1.15,2)}") \ No newline at end of file diff --git a/02_estructuras/p99_gatos_felices_Media_pesos.py b/02_estructuras/p99_gatos_felices_Media_pesos.py new file mode 100644 index 0000000..8c9c45f --- /dev/null +++ b/02_estructuras/p99_gatos_felices_Media_pesos.py @@ -0,0 +1,10 @@ + +numeroGatos=int(3); + +peso1=float(input("Dame el peso de un gato: ")) +peso2=float(input("Dame el peso de un segundo gato: ")) +peso3=float(input("Dame el peso de un tercer gato: ")) + +media=(peso1+peso2+peso3)/numeroGatos + +print (f"la media de {peso1}, {peso2}, {peso3} es {media}") \ No newline at end of file diff --git a/03_control_flujo/Autonomos.py b/03_control_flujo/Autonomos.py new file mode 100644 index 0000000..f800e55 --- /dev/null +++ b/03_control_flujo/Autonomos.py @@ -0,0 +1,53 @@ + + + + +## Autónomos + +#1. Recorre una lista de gatos y imprime sus nombres. + +listagatos={"Isidoro","neko", "salchipapa","Garfield","Meow"} + +for nombre in listagatos: + print(nombre) +#2. Cuenta letras en un string usando un bucle. + +contaLetras="buho" + +i=0 +while(i0: + print("es positivo") + + +if numero<0: + print("es negativo"); + + diff --git a/03_control_flujo/Guiado2_SumaAcumulada.py b/03_control_flujo/Guiado2_SumaAcumulada.py new file mode 100644 index 0000000..1086d62 --- /dev/null +++ b/03_control_flujo/Guiado2_SumaAcumulada.py @@ -0,0 +1,17 @@ +print("Acumulador de números") + +acumulador = 0.0 + +while True: + entrada = input("Dame un número o escribe FIN para salir: ") + + if entrada.lower() == "fin": + break + + try: + numero = float(entrada) + acumulador += numero + except ValueError: + print("valor incorrecto") + +print(f"el total es: {acumulador}") diff --git a/03_control_flujo/ejercicio_guiado/calculadora_v3.py b/03_control_flujo/ejercicio_guiado/calculadora_v3.py index 7a7cfa6..5384fd5 100644 --- a/03_control_flujo/ejercicio_guiado/calculadora_v3.py +++ b/03_control_flujo/ejercicio_guiado/calculadora_v3.py @@ -76,7 +76,22 @@ # TODO 9: Muestra el resultado con f-string - print(f"✅ {num1} {simbolo} {num2} = {resultado:.2f}") + print(f"\n✅ {num1} {simbolo} {num2} = {resultado:.2f}") + + + try: + if (int(resultado)==0): + print ("Es valor cero"); + + if (int(resultado)>0): + print ("Es positivo"); + + + if (int(resultado)<0): + print ("Es negativo"); + + except ValueError: + print(f"{resultado} no es un numero") # ¡Excelente trabajo! Ahora tienes una calculadora interactiva que: diff --git a/03_control_flujo/p1_casting.py b/03_control_flujo/p1_casting.py new file mode 100644 index 0000000..fe75604 --- /dev/null +++ b/03_control_flujo/p1_casting.py @@ -0,0 +1,10 @@ +print ("Dame una variable: ") +var1= input() + +try: + var1=int(var1); + print (f"Respuesta: {var1}") +except: + print ("Entrada invalida") + + diff --git a/03_control_flujo/p1_lista_de_Nombres_de_gatos.py b/03_control_flujo/p1_lista_de_Nombres_de_gatos.py new file mode 100644 index 0000000..7b17e1a --- /dev/null +++ b/03_control_flujo/p1_lista_de_Nombres_de_gatos.py @@ -0,0 +1,4 @@ +listagatos={"Isidoro","neko", "salchipapa","Garfield","Meow"} + +for nombre in listagatos: + print(nombre) \ No newline at end of file diff --git a/03_control_flujo/p2_contarLetrasString.py b/03_control_flujo/p2_contarLetrasString.py new file mode 100644 index 0000000..c4b6c61 --- /dev/null +++ b/03_control_flujo/p2_contarLetrasString.py @@ -0,0 +1,8 @@ +contaLetras="buho" + +i=0 +while(i 0: + print("El promedio es:", suma / contador); +else: + print("No ingresaste ningun numero valido."); diff --git a/04_funciones/p5_validarEdad.py b/04_funciones/p5_validarEdad.py new file mode 100644 index 0000000..c8ccd2a --- /dev/null +++ b/04_funciones/p5_validarEdad.py @@ -0,0 +1,13 @@ + +edad=input("Dame una edad: "); + +try: + edad=int(edad); + if (edad>=0): + print (f"la edad es: {edad}") + else: + print ("no puede ser negativa la edad") + +except ValueError: + print(f"-- ERROR, '{edad}'. No es un valor valido --") + diff --git a/04_funciones/p99_bigotesFelicesEdad.py b/04_funciones/p99_bigotesFelicesEdad.py new file mode 100644 index 0000000..367e13b --- /dev/null +++ b/04_funciones/p99_bigotesFelicesEdad.py @@ -0,0 +1,15 @@ + +gatos=[{"nombre":"Garfield","edad":5}, + {"nombre":"Neko","edad":2}, + {"nombre":"Saturno","edad":7}, + {"nombre":"sardina","edad":1}, + {"nombre":"Brujo","edad":19}, + ] + +edad=5; +print (f"\nGatos con mas de {edad} años \n"); + +for cat in gatos: + if (cat["edad"]>edad): + print(cat["nombre"],cat["edad"], " años") + \ No newline at end of file diff --git a/05_colecciones/Guiado1_ListaDeGatos.py b/05_colecciones/Guiado1_ListaDeGatos.py new file mode 100644 index 0000000..dd958db --- /dev/null +++ b/05_colecciones/Guiado1_ListaDeGatos.py @@ -0,0 +1,3 @@ +gatos = ["Neko", "Luna", "Aquamarina"] +for i, nombre in enumerate(gatos, start=1): + print(f" {i}.{nombre}") \ No newline at end of file diff --git a/05_colecciones/guiado2_DiccionarioSimple.py b/05_colecciones/guiado2_DiccionarioSimple.py new file mode 100644 index 0000000..0057320 --- /dev/null +++ b/05_colecciones/guiado2_DiccionarioSimple.py @@ -0,0 +1,10 @@ +diccionario={ + "Mishi":{ "edad": 3}, + "Garfield":{"edad":5}, + "Neko":{"edad":2}, + "Saturno":{"edad":7}, + "sardina":{"edad":1}, + "Brujo":{"edad":19}} + +buscar="Garfield" +print(f"A buscar {buscar}", diccionario.get(buscar)) \ No newline at end of file diff --git a/05_colecciones/p1_vacunasSet.py b/05_colecciones/p1_vacunasSet.py new file mode 100644 index 0000000..979bf99 --- /dev/null +++ b/05_colecciones/p1_vacunasSet.py @@ -0,0 +1,6 @@ +vacunas={"rabia","Nemesis","tetanos", } + +vacunas.add("virus T"); + +for v in vacunas: + print(v) \ No newline at end of file diff --git a/05_colecciones/p2_coleccionesNombreEdad.py b/05_colecciones/p2_coleccionesNombreEdad.py new file mode 100644 index 0000000..d40b9e3 --- /dev/null +++ b/05_colecciones/p2_coleccionesNombreEdad.py @@ -0,0 +1,24 @@ +nombre = [ + {"nombre": "Garfield"}, + {"nombre": "Neko"}, + {"nombre": "Saturno"}, + {"nombre": "Sardina"}, + {"nombre": "Brujo"}, +] + +edades = [ + {"edad": 7}, + {"edad": 4}, + {"edad": 8}, + {"edad": 9}, + {"edad": 3}, +] + +ficha = [] + + +for n, e in zip(nombre, edades): + ficha.append(f"{n['nombre']}, {e['edad']} años") + +for f in ficha: + print(f) diff --git a/05_colecciones/p3_concurrencia_string_diccionario.py b/05_colecciones/p3_concurrencia_string_diccionario.py new file mode 100644 index 0000000..0b3680c --- /dev/null +++ b/05_colecciones/p3_concurrencia_string_diccionario.py @@ -0,0 +1,10 @@ + +lista =["gato pardo","gato blanco","gato blanquecino","perro pardo","caballo albino"] + + +palabraBuscar="blan" + +for l in lista: + if palabraBuscar in l: + print(l); + diff --git a/05_colecciones/p4_slicing.py b/05_colecciones/p4_slicing.py new file mode 100644 index 0000000..8f82ea5 --- /dev/null +++ b/05_colecciones/p4_slicing.py @@ -0,0 +1,7 @@ +numeros = ["1", "2", "3", "4", "5","6","7","8","9","0"] + +print(numeros[2:5]) +print(numeros[:4]) +print(numeros[2:]) +print(numeros[::2]) +print(numeros[::-1]) \ No newline at end of file diff --git a/05_colecciones/p5_reporte.py b/05_colecciones/p5_reporte.py new file mode 100644 index 0000000..3cfdf64 --- /dev/null +++ b/05_colecciones/p5_reporte.py @@ -0,0 +1,9 @@ +gatos=[{"nombre":"Garfield","edad":5}, + {"nombre":"Neko","edad":2}, + {"nombre":"Saturno","edad":7}, + {"nombre":"sardina","edad":1}, + {"nombre":"Gato de brujo","edad":19}, + ] + +for cat in gatos: + print (f"El gato se llama {cat["nombre"]} y su edad es: {cat["edad"]}") \ No newline at end of file diff --git a/06_archivos_y_modulos/Guiado1_guardar_3Lineas.py b/06_archivos_y_modulos/Guiado1_guardar_3Lineas.py new file mode 100644 index 0000000..2c5eb23 --- /dev/null +++ b/06_archivos_y_modulos/Guiado1_guardar_3Lineas.py @@ -0,0 +1,17 @@ + + +gatos = "gato 1","gato 2","gato 3" + +ruta="./escribir.txt" + + +#guardar +with open(ruta,"w",encoding="UTF-8") as f: + for g in gatos: + f.write(f"{g}\n") + f.close() + + + + + \ No newline at end of file diff --git a/06_archivos_y_modulos/Guiado2_leerLineas.py b/06_archivos_y_modulos/Guiado2_leerLineas.py new file mode 100644 index 0000000..c41ca68 --- /dev/null +++ b/06_archivos_y_modulos/Guiado2_leerLineas.py @@ -0,0 +1,8 @@ +#2. Crea un módulo `utiles.py` con `leer_lineas(ruta)` y `guardar_lineas(ruta, lineas)`. + +#leer y mostrar +ruta="./escribir.txt" +print("Mostrar los datos leidos:\n") +with open(ruta, "r", encoding="utf-8") as x: + for i, linea in enumerate(x, start=1): + print(f" {linea.strip()}") \ No newline at end of file diff --git a/06_archivos_y_modulos/ejercicio_guiado/calculadora_v6.py b/06_archivos_y_modulos/ejercicio_guiado/calculadora_v6.py index 27d34ed..8c3cac1 100644 --- a/06_archivos_y_modulos/ejercicio_guiado/calculadora_v6.py +++ b/06_archivos_y_modulos/ejercicio_guiado/calculadora_v6.py @@ -21,7 +21,7 @@ """ # TODO 1: Importa el módulo json -# import json +import json # Nombre del archivo donde se guardará el historial @@ -107,37 +107,37 @@ def cargar_historial(): Lista con el historial cargado, o lista vacía si no existe el archivo. """ # TODO 2: Intenta cargar el archivo JSON - # try: - # with open(ARCHIVO_HISTORIAL, "r", encoding="utf-8") as archivo: - # datos = json.load(archivo) - # print(f"✅ Historial cargado: {len(datos)} operaciones") - # return datos - # except FileNotFoundError: + try: + with open(ARCHIVO_HISTORIAL, "r", encoding="utf-8") as archivo: + datos = json.load(archivo) + print(f"✅ Historial cargado: {len(datos)} operaciones") + return datos + except FileNotFoundError: # # El archivo no existe (primera vez que se ejecuta) - # print("📝 No hay historial previo, iniciando uno nuevo") - # return [] + print("📝 No hay historial previo, iniciando uno nuevo") + return [] # except json.JSONDecodeError: # # El archivo existe pero está corrupto - # print("⚠️ Archivo de historial corrupto, iniciando uno nuevo") - # return [] + print("⚠️ Archivo de historial corrupto, iniciando uno nuevo") + return [] - pass + return [] # Borra esto cuando implementes la función def guardar_historial_archivo(): """Guarda el historial actual en el archivo JSON.""" # TODO 3: Guarda el historial en el archivo JSON - # try: - # with open(ARCHIVO_HISTORIAL, "w", encoding="utf-8") as archivo: - # # indent=2 hace que el JSON sea más legible - # # ensure_ascii=False permite emojis y caracteres especiales - # json.dump(historial, archivo, indent=2, ensure_ascii=False) - # print("✅ Historial guardado correctamente") - # except Exception as e: - # print(f"❌ Error al guardar el historial: {e}") + try: + with open(ARCHIVO_HISTORIAL, "w", encoding="utf-8") as archivo: + # indent=2 hace que el JSON sea más legible + # ensure_ascii=False permite emojis y caracteres especiales + json.dump(historial, archivo, indent=2, ensure_ascii=False) + print("✅ Historial guardado correctamente") + except Exception as e: + print(f"❌ Error al guardar el historial: {e}") + - pass def limpiar_historial(): @@ -146,23 +146,23 @@ def limpiar_historial(): # TODO 4: Limpia el historial # Pide confirmación al usuario - # confirmacion = input("⚠️ ¿Estás seguro de que quieres limpiar el historial? (s/n): ") - # if confirmacion.lower() != "s": - # print("❌ Operación cancelada") - # return + confirmacion = input("⚠️ ¿Estás seguro de que quieres limpiar el historial? (s/n): ") + if confirmacion.lower() != "s": + print("❌ Operación cancelada") + return # Vacía la lista en memoria - # historial = [] + historial = [] # Elimina el archivo si existe - # try: - # if os.path.exists(ARCHIVO_HISTORIAL): - # os.remove(ARCHIVO_HISTORIAL) - # print("🗑️ Historial limpiado correctamente") - # except Exception as e: - # print(f"❌ Error al eliminar el archivo: {e}") + try: + if os.path.exists(ARCHIVO_HISTORIAL): + os.remove(ARCHIVO_HISTORIAL) + print("🗑️ Historial limpiado correctamente") + except Exception as e: + print(f"❌ Error al eliminar el archivo: {e}") - pass + # ===== FUNCIÓN PRINCIPAL ===== @@ -171,59 +171,59 @@ def main(): """Función principal de la calculadora.""" # TODO 5: Carga el historial al iniciar - # global historial - # print("🔄 Cargando historial...") - # historial = cargar_historial() + global historial + print("🔄 Cargando historial...") + historial = cargar_historial() - # while True: - # mostrar_menu() - # opcion = input("\nElige una opción: ") + while True: + mostrar_menu() + opcion = input("\nElige una opción: ") # TODO 6: Actualiza la condición de salir (ahora es opción 7) - # if opcion == "7": - # print("💾 Guardando historial...") - # guardar_historial_archivo() - # print("¡Hasta pronto! 👋") - # break + if opcion == "7": + print("💾 Guardando historial...") + guardar_historial_archivo() + print("¡Hasta pronto! 👋") + break # TODO 7: Añade la opción 5 (ver historial) - # if opcion == "5": - # mostrar_historial() - # continue + if opcion == "5": + mostrar_historial() + continue # TODO 8: Añade la opción 6 (limpiar historial) - # if opcion == "6": - # limpiar_historial() - # continue + if opcion == "6": + limpiar_historial() + continue # TODO 9: Actualiza la validación de opciones (ahora son 1-6) - # if opcion not in ["1", "2", "3", "4", "5", "6"]: - # print("❌ Opción no válida") - # continue - - # num1, num2 = obtener_numeros() - - # if opcion == "4" and num2 == 0: - # print("❌ No se puede dividir por cero") - # continue - - # if opcion == "1": - # resultado = sumar(num1, num2) - # simbolo = "+" - # elif opcion == "2": - # resultado = restar(num1, num2) - # simbolo = "-" - # elif opcion == "3": - # resultado = multiplicar(num1, num2) - # simbolo = "*" - # elif opcion == "4": - # resultado = dividir(num1, num2) - # simbolo = "/" - - # print(f"✅ {num1} {simbolo} {num2} = {resultado:.2f}") - # guardar_operacion(num1, num2, simbolo, resultado) - - pass + if opcion not in ["1", "2", "3", "4", "5", "6"]: + print("❌ Opción no válida") + continue + + num1, num2 = obtener_numeros() + + if opcion == "4" and num2 == 0: + print("❌ No se puede dividir por cero") + continue + + if opcion == "1": + resultado = sumar(num1, num2) + simbolo = "+" + elif opcion == "2": + resultado = restar(num1, num2) + simbolo = "-" + elif opcion == "3": + resultado = multiplicar(num1, num2) + simbolo = "*" + elif opcion == "4": + resultado = dividir(num1, num2) + simbolo = "/" + + print(f"✅ {num1} {simbolo} {num2} = {resultado:.2f}") + guardar_operacion(num1, num2, simbolo, resultado) + + if __name__ == "__main__": diff --git a/06_archivos_y_modulos/p1_gatosCSV.py b/06_archivos_y_modulos/p1_gatosCSV.py new file mode 100644 index 0000000..d64e6f1 --- /dev/null +++ b/06_archivos_y_modulos/p1_gatosCSV.py @@ -0,0 +1,27 @@ +import json + +gatos=[{"nombre":"Garfield","edad":5}, + {"nombre":"Neko","edad":2}, + {"nombre":"Saturno","edad":7}, + {"nombre":"sardina","edad":1}, + {"nombre":"Gato de brujo","edad":19}, + ] + + +#guardar diccionario + +ruta = "P1_gatos.csv" +with open(ruta, "w", encoding="utf-8") as f: + for g in gatos: + f.write(f"{g}") + + f.close() + + + + +#Mostrar +with open(ruta, "r", encoding="utf-8") as x: + for i, linea in enumerate(x, start=1): + print(f"{i}: {linea.strip()}") + diff --git a/06_archivos_y_modulos/p3_leer_guardar_con_utiles.py b/06_archivos_y_modulos/p3_leer_guardar_con_utiles.py new file mode 100644 index 0000000..d5b0473 --- /dev/null +++ b/06_archivos_y_modulos/p3_leer_guardar_con_utiles.py @@ -0,0 +1,16 @@ +import utiles + +ruta = "datos.txt" +lineas_a_guardar = ["Linea 1", "Linea 2", "Linea 3"] + +# Guardar + +utiles.guardar_lineas(ruta, lineas_a_guardar) +print("\n-- Líneas guardadas") + +# Leer +lineas_leidas = utiles.leer_lineas(ruta) +print("-- Lineas leidas desde archivo") +for linea in lineas_leidas: + print("\t" + linea) + diff --git a/06_archivos_y_modulos/p4_FileNotFoundError.py b/06_archivos_y_modulos/p4_FileNotFoundError.py new file mode 100644 index 0000000..9be7908 --- /dev/null +++ b/06_archivos_y_modulos/p4_FileNotFoundError.py @@ -0,0 +1,13 @@ +def leer_lineas(ruta): + print ("\nleyendo...") + try: + with open(ruta, 'r', encoding='utf-8') as archivo: + return [linea.rstrip('\n') for linea in archivo] + except FileNotFoundError: + print(f"El archivo '{ruta}' no existe") + return [] + + + + +print(leer_lineas("./datos.txt")) \ No newline at end of file diff --git a/06_archivos_y_modulos/utiles.py b/06_archivos_y_modulos/utiles.py new file mode 100644 index 0000000..a437108 --- /dev/null +++ b/06_archivos_y_modulos/utiles.py @@ -0,0 +1,14 @@ + +def leer_lineas(ruta): + try: + with open(ruta, 'r', encoding='utf-8') as archivo: + return [linea.rstrip('\n') for linea in archivo] + except FileNotFoundError: + print(f"El archivo '{ruta}' no existe.") + return [] + + +def guardar_lineas(ruta, lineas): + with open(ruta, 'w', encoding='utf-8') as archivo: + for linea in lineas: + archivo.write(f"{linea}\n") diff --git a/07_mini_proyectos/p1_EstadisticasGatos.py b/07_mini_proyectos/p1_EstadisticasGatos.py new file mode 100644 index 0000000..a32f1e6 --- /dev/null +++ b/07_mini_proyectos/p1_EstadisticasGatos.py @@ -0,0 +1,31 @@ +## 1) Estadísticas del refugio de gatos +#- Entrada: archivo o lista de pesos y edades. +#- Tareas: conteo, media, mediana simple, top-k más pesados. +#- Salida: resumen por pantalla y guardado opcional a archivo. +import p1_funciones + +#variables +gatos=[ + {"nombre":"Luna", "kg":5, "edad":3}, + {"nombre":"Michi", "kg":10, "edad":9}, + {"nombre":"Bola de nieve II","kg":15, "edad":6}, + ] + +ruta="gatos.txt" + +informacion=[] +#main +informacion.append( f"Conteos de gatos: {p1_funciones.contador(gatos)}\n" ) +informacion.append("Peso medio de los gatos: {p1_funciones.media(gatos)}\n") +informacion.append(f"Peso mediana de los gatos: {p1_funciones.mediana(gatos)}\n") +informacion.append(p1_funciones.GatoMasPesado(gatos)) +p1_funciones.guardarGatos(ruta,informacion) +p1_funciones.leerGatos(ruta) + + + + + + + + diff --git a/07_mini_proyectos/p1_funciones.py b/07_mini_proyectos/p1_funciones.py new file mode 100644 index 0000000..e36416c --- /dev/null +++ b/07_mini_proyectos/p1_funciones.py @@ -0,0 +1,45 @@ + +def contador(g): + contador=0; + for i in g: + contador+=1; + return(contador); + + +def media(g): + total = sum(gato["kg"] for gato in g) + if(total==0): + return 0; + return(total/len(g)); + +def mediana(g): + pesos = sorted(gato["kg"] for gato in g) + n = len(pesos) + if n % 2 == 1: + return pesos[n // 2] + else: + return (pesos[n // 2 - 1] + pesos[n // 2]) / 2 + +def GatoMasPesado(g): + pesoMax=0; + GatoMasPesado=""; + for i in g: + if i["kg"]>pesoMax: + pesoMax=float(i["kg"]) + GatoMasPesado=i["nombre"]; + + return (f"--{GatoMasPesado} es el felino con mas peso es con {pesoMax} Kg." ) + + +def guardarGatos(ruta,info): + with open(ruta, 'w', encoding='utf-8') as archivo: + archivo.write(f"{info}") + +def leerGatos(ruta): + print("\tleyendo Gatos: ") + try: + with open(ruta, 'r', encoding='utf-8') as archivo: + for linea in archivo: + print ( f"{linea} \n" ); + except FileNotFoundError: + print(f"El archivo '{ruta}' no existe.") \ No newline at end of file diff --git a/07_mini_proyectos/tickets.py b/07_mini_proyectos/tickets.py new file mode 100644 index 0000000..cfcbe7a --- /dev/null +++ b/07_mini_proyectos/tickets.py @@ -0,0 +1,27 @@ +## 2) Mini sistema de tickets +#- Usa listas y diccionarios para manejar tickets (id, título, estado). +#- Operaciones: crear, listar, cerrar. +#- Persistencia opcional en archivo. +id=9; + +tickets=[ + {1,"Vampiros","en Curso"}, + {2,"pinguinos","en Curso"}, + {3,"bella","en Curso"}, + {4,"Pinocho","Caducado"}, + {5,"Gnomos","en Curso"}, + {6,"Ogros III","en Curso"}, + {7,"robot la venganza","Caducado"}, + {9,"robot II, la continuacion de la venganza","en Curso"}, + ] + +def menu(): + + while(True): + print("1: Anadir Pelicula: ") + print("2: Listar Peliculas: ") + print("3: Cambiar estado: ") + opcion = input("¿Que opcion quieres?: ") + + pelicula=input("Dame el nombre de la pelicula?") + pelicula=input("Dame el nombre de la pelicula?") diff --git a/datos.txt b/datos.txt new file mode 100644 index 0000000..b478d26 --- /dev/null +++ b/datos.txt @@ -0,0 +1,3 @@ +Linea 1 +Linea 2 +Linea 3 diff --git a/escribir.txt b/escribir.txt new file mode 100644 index 0000000..6202e9f --- /dev/null +++ b/escribir.txt @@ -0,0 +1,3 @@ +gato 1 +gato 2 +gato 3 diff --git a/gatos.json b/gatos.json new file mode 100644 index 0000000..2927467 --- /dev/null +++ b/gatos.json @@ -0,0 +1,5 @@ +[ + "gato 1", + "gato 4", + "gato 3" +] \ No newline at end of file diff --git a/gatos.txt b/gatos.txt new file mode 100644 index 0000000..ff934d8 --- /dev/null +++ b/gatos.txt @@ -0,0 +1 @@ +['Conteos de gatos: 3\n', 'Peso medio de los gatos: {p1_funciones.media(gatos)}\n', 'Peso mediana de los gatos: 10\n', '--Bola de nieve II es el felino con mas peso es con 15.0 Kg.'] \ No newline at end of file