Advertisement
teslariu

excepciones

Oct 7th, 2023 (edited)
1,142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.95 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. # Script que divide dos numeros
  5. def validar_numero(n):
  6.     while True:
  7.         try:
  8.             a = float(input(f"Ingrese un nro {n}: "))
  9.         except ValueError:
  10.             print("Error: no ha ingresado un nro")
  11.         else:
  12.             return a
  13.  
  14.  
  15. def dividir(a,b):
  16.     try:
  17.         cociente = a / b
  18.    
  19.     except ZeroDivisionError:
  20.         return "No se puede dividir por cero..."
  21.  
  22.     except IOError:
  23.         return "Error de lectura de datos"
  24.  
  25.     else:
  26.         return f"El cociente entre {a} y {b} es {a/b}"
  27.    
  28.  
  29.  
  30.  
  31. a = validar_numero("a")
  32. b = validar_numero("b")
  33. print(dividir(a,b))
  34.  
  35.  
  36. # Lanzar excepciones
  37.  
  38. def sumar(a,b):
  39.     """Función que implementa la suma de dos números.
  40.     Lanzará una excepción si los parámetros no son del tipo correcto"""
  41.     if not isinstance(a,(float,int)) or not isinstance(b,(float,int)):
  42.         raise TypeError("Se requieren dos números como parámetros")
  43.     return a+b
  44.    
  45.    
  46.    
  47.    
  48. print(sumar(2,3.2))
  49. print(sumar("Hola","Chau"))    
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement