Why my function results in infinite loop? I want to return the value of the exponential base (2**3 which should return 8)?
def iterPower(base, exp):
i = 0
answer = 0
while exp >= 0:
if i!= exp:
answer = base * (base * i)
i += 1
else:
answer = base * (base * i)
return answer
iterPower(2,3)
you are stucked in the infinite loop because of while
condition is comparing exp
which is not decreasing
I simplified your code to:
def iter_power(base, exp):
answer = 1
while exp > 0:
answer *= base
exp -= 1
return answer
print(iter_power(2, 3)) # 8
print(iter_power(2, 0)) # 1
print(iter_power(2, 8)) # 256