In Python, Use a for-Loop and Multiplication to Create a Power Function

In Python, Use a for-Loop and Multiplication to Create a Power Function

I need a function that raises a number to a said power by using multiplication in a for-loop.This is what i have so far:

def power(num, power): 
    for x in range(power):
        number = num * num
    return number

print(power(3, 4))
1

2 Answers

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

It should be -

def power(num,pow):
  number = 1
  for x in range(pow):
    number=number*num
  return number

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.