Advertisement
teslariu

cuadratica

Aug 17th, 2022
914
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.74 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. """
  5. Script que calcula las raices de una ecuación cuadratica y almacena
  6. los resultados en un archivo
  7. >>> Ingrese el término cuadratico: 1
  8. >>> Ingrese el término lineal: 10
  9. >>> Ingrese el término independiente: 5
  10. >>> No existen raíces reales
  11. """
  12. import datetime
  13. from math import sqrt
  14.  
  15.  
  16. def ingresar(termino="numérico"):
  17.     while True:
  18.         try:
  19.             dato = float(input(f"Ingrese el término {termino}: "))
  20.         except ValueError:
  21.             print("Debe ingresar un número")
  22.         else:
  23.             if termino == "cuadratico" and not dato:
  24.                 print("El término cuadrático debe ser distinto de cero")
  25.             else:
  26.                 return dato
  27.  
  28.                
  29. def calcular_raices(a,b,c):
  30.     delta = b**2 - 4*a*c
  31.     if not delta:
  32.         raiz = -1*b / (2*a)
  33.         return raiz
  34.    
  35.     elif delta > 0:
  36.         raiz1 = (-1*b + sqrt(delta)) / (2*a)
  37.         raiz2 = (-1*b - sqrt(delta)) / (2*a)
  38.         return [raiz1,raiz2]
  39.        
  40.     else:
  41.         return "No existen raíces reales"
  42.  
  43.  
  44. def imprimir(raices):
  45.     if isinstance(raices,float):
  46.         print(f"Existe una única raíz real: {raices:.2f}")
  47.     elif isinstance(raices,list):
  48.         print(f"Existen dos raíces reales: {raices[0]:.2f} y {raices[1]:.2f}")
  49.     else:
  50.         print(raices)
  51.    
  52.  
  53.  
  54.        
  55. def grabar_datos(a,b,c,raices):
  56.     """Guardo los datos en un archivo de texto"""
  57.     f.write(datetime.datetime.now().strftime("%d/%m/%y %H:%M:%S"))
  58.     f.write(f"""
  59.    Parámetros de la parábola:
  60.    -------------------------
  61.    Término cuadrático (a): {a}
  62.    Término lineal (b): {b}
  63.    Término independiente (c): {c}
  64.    Raíces:
  65.    ------
  66.    """)
  67.     if isinstance(raices,float):
  68.         f.write(f"Existe una única raíz real: {raices:.2f}\n\n")
  69.     elif isinstance(raices,list):
  70.         f.write(f"Existen dos raíces reales: {raices[0]:.2f} y {raices[1]:.2f}\n\n")
  71.     else:
  72.         f.write(raices+"\n\n")
  73.  
  74.  
  75.  
  76. if __name__ == '__main__':
  77.     # abro el archivo, si no existe lo creo
  78.     try:
  79.         f = open("cuadratica.txt","x")
  80.     except FileExistsError:
  81.         f = open("cuadratica.txt", "a")
  82.    
  83.     # ejecuto el programa
  84.     while True:
  85.         print("\nCálculo de las raíces reales de una ec. cuadrática")
  86.    
  87.         a = ingresar("cuadratico")
  88.         b = ingresar("lineal")
  89.         c = ingresar("independiente")
  90.         raices = calcular_raices(a,b,c)
  91.         grabar_datos(a,b,c,raices)
  92.         imprimir(raices)
  93.    
  94.         opcion = input("Presione cualquier tecla para continuar ('1' para salir): ")
  95.         if opcion == "1":
  96.             print("Gracias por usar este programa...")
  97.             f.close()
  98.             break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement