Shawn
Shawn

Reputation: 13

Calculate a value raised to a power with loops

In class we are making a program using loops to raise a number to a power with loops. I have got to this part but I am lost. Looking for any help.

base=int(raw_input("What number do you want to be the base"))
exp=int(raw_input("What do you want to be the power"))

def power(base, exp):
    res=1
    for _ in range(exp):
        number=res*base
    return number
    print number

Upvotes: 1

Views: 3200

Answers (2)

Anshul Goyal
Anshul Goyal

Reputation: 76887

You are overwriting the value of number in each loop, so that the end result is it never changes. Instead, do

base=int(raw_input("What number do you want to be the base"))
exp=int(raw_input("What do you want to be the power"))

def power(base, exp):
    res=1
    for _ in range(exp):
        res = res*base
    print res
    return res

print power(base, exp)

Note that I've put the print statement before the return statement; otherwise it wouldn't have been executed. And finally, there is an extra print statement at the end to call the function. In fact, with this print statement, you don't even need the print in the power() method any longer, so you could as well remove it.

In case you want to do this without the for loop, you can simplify this using

def power(base, exp):
    return base**exp

Upvotes: 1

Amadan
Amadan

Reputation: 198314

  • You never call the function power you defined. Try print power(base, exp) at the end.
  • If you were to call it, it would loop some, then return number, which is res * base, which is 1 * base (since you never change anything, and do the same calculation in the loop every time). Consider res = res * base (or equivalently, res *= base) and return res, not number
  • You would also not print anything, since it is beyond the return statement.

Upvotes: 1

Related Questions