Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Does anyone know how to do recursion on Python? How do I do this:

The built in Python function pow(x,y) returns the number x to the power of y. Write a function that performs this task recursively.

Name it myPow() and have it accept two integers as arguments. You do not have to handle a power less than 1, (myPow(64,.5) for example.

5 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,468 Points

A recursive function is one that calls itself during normal execution. The recursion stops at some minimal condition at which point the recursive calls unwind back to the most outer function call.

Name it myPow() and have it accept two integers as arguments. You do not have to handle a power less than 1, (myPow(64,.5) for example.

# Create a function myPow()
def myPow(int1, int2):
    # minimal case: int2 is 1
    if int2 == 1:
        return int1
    # otherwise 
    # recursively call myPow to get (int1, int2 - 1)
    result = int1 * myPow(int1, int2 - 1)
    return result

The last two lines could be combined to be:

return int1 * myPow(int1, int2 - 1)

Aren't you forgetting the "print" function?

Chris Freeman
Chris Freeman
Treehouse Moderator 68,468 Points

The function intentionally doesn't print, but rather returns the value as an int. A print could be done by:

print(myPow(3, 5))

or assigned to a variable:

three_power_five = myPow(3, 5)

This is what I've got so far:

def myPow(int1, square):
    if square == 1:
        return num
    else:
        return int1 * myPow(int1, square)

# main
a = myPow(7,3)
print(a)

b = myPow(2,6)
print(b)

[MOD: added ```python formatting -cf]

Chris Freeman
Chris Freeman
Treehouse Moderator 68,468 Points

You current code does not decrement square so the return is effectively calling:

return 7 * myPow(7, 3)....

Which turns into 7 to the infinite power. Usually the program will bomb out with an "recursive error limit".

When I input that, the program goes forever and I have to exit out of the shell to kill it

Thanks Chris, I got it