JTT
JTT

Reputation: 9

Python Recursive Power

def main():

    base = input('Please Enter An Integer for the Base: ')
    exponent = input ('Please Enter An Exponent: ')

def power (base, exponent):
    if exponent == 0:
        return base
    else :
        return base * power(base, exponent - 1)
    

main()

SAMPLE OUT:

Enter an integer for the base: 2
Enter an integer for the exponent: 5
2 to the power 5 equals 32

Upvotes: 0

Views: 2122

Answers (2)

Rey
Rey

Reputation: 1

This is sort of working for me, but I get 1000 if I use 10 as base and 2 as the exponent. Trying to figure it out now why the math is wrong.

def main():

   base = float(input('Please Enter An Integer for the Base: '))
   exponent = float(input('Please Enter An Exponent: '))
   result = power(base, exponent)
   print("{} to the power of {} equals {}".format(base, exponent, result))

def power (base, exponent):

   if exponent == 0:
      return base
   else :
      return base * power(base, exponent - 1)
main()

Upvotes: 0

Sam
Sam

Reputation: 9944

If this is Python 3, use string formatting like this:

result = power(base, exponent)
print("{} to the power of {} equals {}".format(base, exponent, result))

In Python 2,

print "%d to the power of %d equals %d" % (base, exponent, result)

Upvotes: 1

Related Questions