It does NOT work except for python

0

! / usr / local / bin / python3

Write an iterative function iterPower​ ​(base,​ ​exp) that calculates the exponential baseexp simply by using successive multiplication.

For example, iterPower (base, exp) must calculate baseexp by multiplying base by itself exp times.

This function must take two values - base can be a float or an integer; exp will be an integer ≥ 0. You must return a numeric value. The code must be iterative - the use of the operator ** is not allowed

def iterPower(base, exp): Raise an integer or decimal number to a whole number, Returns a real number, the result of the power between two numbers.

Parameters:

'base' -- Puede ser entero o decimal
'exp'  -- Debe de ser entero y mayor a 0

Exceptions:     If the parameters are not as expected, it will return an error warning of it

#Se crea el controlador de excepciones
try:
    #Para que exp no sea string se pasa a entero
    exp= int(exp)
    #Para que base no sea string se pasa a int o float, segun sea uno u otro
    if base.count(".")==0:
        base= int(base)
    else:
        base= float(base)
    #Si el exponente es menor a 0 lanza una excepcion persoanlizada
    if exp<0:
        raise ValueError("El exponente no puede ser menor a 0")
    #Se crea el total = 1 ya que 1 es el valor nulo en multiplicaciones
    total=1
    i=0
    #Realiza el bucle exp veces, por cada recorrido se multiplica un num a si mismo
    for i in range(int(exp)):
        total= base*total
    return total

except ValueError as mensaje: 
    #Imprime la excepcion personalizada
    print(mensaje)
except:
    print("No se han insertado bien los parámetros")

The program is executed demanding values

print("\n\n***Programa para calcular las potencias de un número***\n")
base= input("Inserte la base: ")
exp= input("Insere el exponente: ")

The function is called

resultado= iterPower(base,exp)

print("El resultado es: "+str(resultado))

I have to do the following exercise, everything is fine, until I see that it does not collect the general exception, that is, if I do not insert the parameters correctly, an error occurs and the exception does not pick it up, the custom works, but that does not work , I noticed that if I remove the custom from ValueError , the general works, thanks in advance.

    
asked by Antonio Jordan 01.11.2018 в 18:49
source

1 answer

1

you can try this:

try:
   #code
except ValueError as mensaje:
    #catpura un error de valor
    print(mensaje)
except Exception as e:
    print("cualquier error");
else:
    # si no ocurren errores de ningun tipo valor
   print("exitoso!")
finally:
    # si ocurre o no error se imprime
   print("operacion realizada!")

you must go from the most specific to the most global!

    
answered by 01.11.2018 в 19:06