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

Time:01-02

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.

CodePudding user response:

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)

CodePudding user response:

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

CodePudding user response:

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

  • Related