iterative function for calculating exponents without using **

Question:

I need to write a program where I write an iterative function that calculates the exponential of base * exponent without using ** operator in my program.

I have tried the code I have already created but am unsure how to fix my error of “int” object is not callable.

def iterPower (base, exp):
    """Run a program in which the base multiplies itself by the exponent value"""
    exp = 3
    for n in base(exp):
        exp *= base
    return exp

base = 5
exp = 3

print(iterPower(5,3))

The expected result would be the answer of 125, but I am not getting any number due to my errors.

Asked By: thefence2113

||

Answers:

Youre passing in integers so you can’t call 5(3), like base(exp) does. Try using for n in range(exp) instead, it will give you the desired number of iterations.

Answered By: billybob123

You need to multyply base * base exp times:

def iterPower (base, exp):
    """Run a program ion which the base multiplies itself by the exponent value"""
    n = base
    for _ in range(1, exp):
        n *= base
    return n

Results:

>>> iterPower(5, 3)
125
>>> 5**3
125
Answered By: Netwave

Here is an answer using the "While" loop:

result = 1
while exp > 0:
    result *= base
    exp -= 1
return result
Answered By: Augusto Moser
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.