teslariu

excepciones y raise

Jun 29th, 2023
818
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.00 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. """
  5. Python 3.10.5 (tags/v3.10.5:f377153, Jun  6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)] on win32
  6. Type "help", "copyright", "credits" or "license" for more information.
  7. >>> # excepciones: son un modelo de manejo de errores
  8. >>> 25/0
  9. Traceback (most recent call last):
  10.  File "<stdin>", line 1, in <module>
  11. ZeroDivisionError: division by zero
  12. >>> 25 + "er"
  13. Traceback (most recent call last):
  14.  File "<stdin>", line 1, in <module>
  15. TypeError: unsupported operand type(s) for +: 'int' and 'str'
  16. >>> int("er")
  17. Traceback (most recent call last):
  18.  File "<stdin>", line 1, in <module>
  19. ValueError: invalid literal for int() with base 10: 'er'
  20. >>> lista = [1,2]
  21. >>> lista[2]
  22. Traceback (most recent call last):
  23.  File "<stdin>", line 1, in <module>
  24. IndexError: list index out of range
  25. >>> dicc = {"red":"rojo", "blue":"azul"}
  26. >>> dicc["yellow"]
  27. Traceback (most recent call last):
  28.  File "<stdin>", line 1, in <module>
  29. KeyError: 'yellow'
  30. >>>
  31.  
  32. # Script que pide dos numeros y devuelve su cociente
  33.  
  34. a = float(input("Dividendo: "))
  35. b = float(input("Divisor: "))
  36.  
  37. try:
  38.    print(f"{a}/{b} = {a/b}")
  39. except ZeroDivisionError:
  40.    print("No se puede dividir por cero")
  41. else:
  42.    print("Que suerte, no hubo errores")
  43. finally:
  44.    print("Adios") # esto se ejecuta siempre
  45.  
  46. try:
  47.    n = 2 / int("0")
  48. except ValueError:
  49.    print("Error de valor: debe ingresar un numero")
  50. except ZeroDivisionError:
  51.    print("Error de division por cero")
  52. else:
  53.    print(n)
  54.  
  55. # otro enfoque
  56. try:
  57.    n = 2 / int("sdfdsf")
  58. except (ValueError, ZeroDivisionError):
  59.    print("Error de valor o de division por cero")
  60. else:
  61.    print(n)
  62. """
  63.  
  64. def sumar(a,b):
  65.     """Función que recibe como argumentos dos numeros y devuelve su suma"""
  66.     if not isinstance(a,(int,float)) or not isinstance(b,(int,float)):
  67.         raise TypeError("Se requieren dos números")
  68.     return a + b
  69.    
  70.    
  71. print(sumar(1,2))
  72. print(sumar("Ale","jandro"))
  73. print(sumar([1,2,3],["hola","chau"]))
Advertisement
Add Comment
Please, Sign In to add comment