Advertisement
teslariu

exception

May 5th, 2021
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.06 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. def ingresar_numero():
  5.     while True:
  6.         try:
  7.             numero = float(input("Ingrese un numero: "))
  8.         except ValueError:
  9.             print("No ha ingresado un número")
  10.         else:
  11.             print(f"Numero ingresado: {numero}")
  12.             return numero
  13.  
  14.            
  15. def dividir(a,b):
  16.     """Función que toma como argumento dos float y, en el caso de ser
  17.    b distinto de cero, devuelve el resultado de la división a/b. Si b
  18.    es cero, lanza una excepción ZeroDivisionError"""
  19.     if b:
  20.         return a/b
  21.     else:
  22.         raise ZeroDivisionError
  23.  
  24.  
  25.    
  26. def sumar(a,b):
  27.     return a+b
  28.    
  29.    
  30. a = ingresar_numero()
  31. b = ingresar_numero()
  32.  
  33. suma = sumar(a,b)
  34.  
  35.  
  36.  
  37. try:
  38.     cociente = dividir(a,b)
  39. except ZeroDivisionError:
  40.     print("No se puede dividir por cero")
  41. else:
  42.     print(f"Cociente: {cociente}")
  43. finally:
  44.     print(f"Suma: {suma}")
  45.  
  46.  
  47.  
  48. # raise es la palabra reservada que lanza una excepcion
  49.    
  50. # try/except
  51. # try/except/else
  52. # try/except/else/finally
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement