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

Kenneth and Recursion

Kenneth mentions this function is a good example of recursion:

def get_locations(cells):

    monster = random.choice(cells)
    door = random.choice(cells)
    player = random.choice(cells)

    if monster == door or monster == player or door == player:
        monster, door, player = get_locations(cells)

    return monster, door, player

We call get_locations() again if any of the values are the same, which makes sense. But why do we set it equal to monster, door, and player? Why wouldn't calling just get_locations(cells) have done the trick since that is what the function is doing?

2 Answers

Because the original call needs to return the correct result.

Recursion is very tricky. Pretend the outermost function call recurses.

Main function call -> Recursion Call |               Return value received from call
                                     v              ^
                                       Return value |

:warning: Note that the recursion call's return isn't the same as the main function call's return.

The recursion call's return value is passed on to where the function was called, in this case the main function call. Then the main function call returns to who called that function, which is somewhere outside the function.

If the function goes deeper, it might look like this:

Outermost call | ---------------------------------------------------- Return to call outside of function       
               v ---------------------------------------------------- ^
               Inner call | ---------------------------- Return value |
                          v ---------------------------- ^
                          Innermost call -> Return value |

Does this make a little more sense? :smiley:

:grin: I hope this helps.

:dizzy: ~Alex :dizzy:

The illustrations you provided are perfect! It makes a lot of sense now, thanks Alex!

No problem :)

In this case, the function is designed get three random locations (monstor, door and player), so when any two are the same, we call the same function again and it tries to set all three again. It is not designed to set one at a time.