Svoboda805
Svoboda805

Reputation: 21

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))

Upvotes: 1

Views: 16327

Answers (2)

brunsgaard
brunsgaard

Reputation: 5168

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

Upvotes: 3

theharshest
theharshest

Reputation: 7867

It should be -

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

Upvotes: 0

Related Questions