Advertisement
teslariu

raices.py

Aug 23rd, 2023
780
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.49 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. """
  5. ========= ===============================================================
  6. Character Meaning
  7. --------- ---------------------------------------------------------------
  8. 'r'       open for reading (default)
  9. 'w'       open for writing, truncating the file first
  10. 'x'       create a new file and open it for writing
  11. 'a'       open for writing, appending to the end of the file if it exists
  12. 'b'       binary mode
  13. 't'       text mode (default)
  14. '+'       open a disk file for updating (reading and writing)
  15. 'U'       universal newline mode (deprecated)
  16. ========= ===============================================================
  17.  
  18. The default mode is 'rt' (open for reading text). For binary random
  19. access, the mode 'w+b' opens and truncates the file to 0 bytes, while
  20. 'r+b' opens the file without truncation. The 'x' mode implies 'w' and
  21. raises an `FileExistsError` if the file already exists.
  22.  
  23. # Script que crea un archivo con temperaturas expresadas en ºC y a partir
  24. # de él, genera otro archivo pero con las temperaturas en ºF
  25.  
  26. # creo un archivo vacío y le agrego datos
  27. try:
  28.     f = open("celsius.txt","x")
  29. except FileExistsError:
  30.     f = open("celsius.txt","a")
  31.  
  32. # creo una lista con los datos a guardar
  33. datos = ["12ºC\n", "-2.5ºC\n", "11ºC\n", "0ºC\n"]
  34.  
  35. # escribo los datos en el archivo y lo cierro
  36. f.writelines(datos)
  37. f.close()
  38.  
  39. # abro el archivo nuevamente porque me olvidé de agregar un dato
  40. # with cierra automáticamente, no necesito close()
  41. with open("celsius.txt","a") as f:
  42.     f.write("10ºC\n")
  43.  
  44.  
  45. # creo el archivo farenheit:   
  46. try:
  47.     f2 = open("farenheit.txt","x")
  48. except FileExistsError:
  49.     f2 = open("farenheit.txt","a")
  50.    
  51. f = open("celsius.txt")
  52. # itero linea a linea celsius, convierto a ºF y la grabo
  53. for temp in f.readlines():
  54.     valor, _ = temp.split("º")
  55.     valor = float(valor) * 1.8 + 32
  56.     f2.write(f"{valor:.1f}ºF\n")
  57.  
  58. # cierro archivos
  59. f.close()
  60. f2.close()
  61. """
  62.  
  63. # Script que calcula las raices de una ec. cuadratica en el campo de
  64. # de los nros reales
  65. # Ej:
  66. # >> Ingrese el termino cuadratico a: 1
  67. # >> Ingrese el término lineal b: 10
  68. # >> Ingrese el término independiente c: 5
  69. # >> No existen raíces
  70. # NOTA: el término cuadrático debe ser distinto de cero
  71.  
  72. from math import sqrt
  73. from datetime import datetime
  74.  
  75. def ingresar_datos(termino):
  76.     while True:
  77.         try:
  78.             n = float(input(f"Ingrese el término {termino}: "))
  79.         except ValueError:
  80.             print("Debe ingresar un número ")
  81.         else:
  82.             if termino == "cuadratico" and n != 0:
  83.                 return n
  84.            
  85.             elif termino != "cuadratico":
  86.                 return n
  87.                
  88.             else:
  89.                 print("Debe ingresar un número distinto de cero")
  90.                
  91.                
  92. def calcular_raices(a,b,c):
  93.     delta = b**2 - 4*a*c
  94.    
  95.     if not delta:
  96.         raiz1 = -1*b / (2*a)
  97.         return raiz1
  98.        
  99.     elif delta > 0:
  100.         raiz1 = (-1*b + sqrt(delta)) / (2*a)
  101.         raiz2 = (-1*b - sqrt(delta)) / (2*a)
  102.         return [raiz1, raiz2]
  103.        
  104.     else:
  105.         return "No existen raices en el campo de los nros reales"
  106.        
  107.  
  108. def guardar_datos(a,b,c,raices):
  109.     # escribo fecha y hora y los parametros de la parabola
  110.     try:
  111.         f = open("cuadratica.txt","x")
  112.     except FileExistsError:
  113.         f = open("cuadratica.txt","a")
  114.     f.write(f"{datetime.now().strftime('%d/%m/%y %H:%M:%S')}\n")
  115.     f.write("Parámetros de la parábola\n")
  116.     f.write(f"Término cuadrático a = {a}\n")
  117.     f.write(f"Término lineal b = {b}\n")
  118.     f.write(f"Término independiente c = {c}\n")
  119.    
  120.     if isinstance(raices, float):
  121.         f.write(f"Raíz única: {raices:.2f}\n")
  122.        
  123.     elif isinstance(raices, list):
  124.         f.write(f"Raíz 1 = {raices[0]}  -  Raiz 2 = {raices[1]}\n")
  125.        
  126.     else:
  127.         f.write(f"{raices}\n")
  128.    
  129.     f.write(f"\n------------------------------------------------------\n\n")
  130.        
  131.  
  132. def imprimir_raices(raices):
  133.     if isinstance(raices, float):
  134.         print(f"Raíz única: {raices}\n")
  135.        
  136.     elif isinstance(raices, list):
  137.         print(f"Raíz 1 = {raices[0]}  -  Raiz 2 = {raices[1]}\n")
  138.        
  139.     else:
  140.         print(raices)
  141.        
  142. def menu():
  143.     print("""
  144.     Menu de opciones
  145.     ------------------
  146.     1. Calcular raices
  147.     2. Salir
  148.     ------------------
  149.     """)
  150.     op = input("Seleccione una opcion: ")
  151.     return op
  152.    
  153.    
  154. while True:
  155.     opcion = menu()
  156.    
  157.     if opcion == "1":
  158.         a = ingresar_datos("cuadratico")
  159.         b = ingresar_datos("lineal")
  160.         c = ingresar_datos("independiente")
  161.        
  162.         raices = calcular_raices(a,b,c)
  163.         guardar_datos(a,b,c,raices)
  164.         imprimir_raices(raices)
  165.        
  166.     elif opcion == "2":
  167.         print("Hasta luego...")
  168.         break
  169.        
  170.     else:
  171.         print("Opcion incorrecta")
  172.    
  173.    
  174.            
  175.  
  176.        
  177.                
  178.  
  179.  
  180.  
  181.  
  182.  
  183.  
  184.  
  185.  
  186.  
  187.  
  188.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement