Why does this for-loop always return the square of the number and not the exponent value?

Question:

I tried to code this into python:
essentially it is a exponent calculator
so for exp(2, 5) it should return 25

def exp(num, pow):
    for i in range(0, pow, 1):
        num1=num*num
    print(num1)
print(exp(2, 5))

why won’t it work?

I expected it to work but it always gives the square of the number.

Asked By: crimson-wind

||

Answers:

Exponential in python is calculated with (**). You can simply do this:

def exp(num, pow):
    return num**pow
print(exp(2, 5))

and this should return the value to the power

Answered By: Kulasangar

You should do num1=num1*num or num=num*num instead of num1=num*num.

If you do num1=num*num, the num1 will always contain the num^2 no matter how long the loop takes.

num1 = num
for i in range(1,n):
    num1=num1*num
return num1

or

for i in range(1,n):
    num=num*num
return num
Answered By: Dhana D.

Each iteration of the loop just multiplies num by itself, once.

Sticking to your existing code as much as possible, you can modify your function to be like this:

def exp(num, pow):
        original_num = num

        for i in range(1,pow,1):
            num = num * original_num
        print(num)
Answered By: suryaya