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 Python Collections (Retired) Dungeon Game Building the Game: Part 1

Ali Mammadov
Ali Mammadov
2,172 Points

Returning get_locations() instead of calling it

Why do we return get_locations() in the procedure of checking for duplicates? Why can't we just call this function? What difference will it make? What does "return some_awesome_function()" expression mean in python?

3 Answers

If you were to just call it without the return statement, the original monster, door, and start values would remain unchanged. Since "return monster, door, start" is the next line of the program, it would return those unchanged values.

By using "return get_locations()", the results of the recursive [1] call are returned.

[1] See http://en.wikipedia.org/wiki/Recursion_%28computer_science%29 for more info on recursion.

Ali Mammadov
Ali Mammadov
2,172 Points

Thanks for clearing it out!

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,425 Points

In the line

return get_locations()

you are calling the function. The function call get_locations() is evaluated, then the results are returned. That line of code is a shortcut and has the same meaning as:

new_locations = get_locations()
return new_locations

Calling a function from within itself is a recursive call that is typically used to break a problem down into smaller chunks. In this usage, the problem isn't broken down but rather simply retried whole. There is a risk that if there were a typo that caused monster, door, or start to always have the same values, in recursion would become infinite. Python will detect this and report RuntimeError: Maximum recursion depth exceeded

Semantically, you're not actually returning the function – which is possible but uses a different syntax: leave off the parentheses.

Leaving off the parentheses is a common typo that is unfortunately valid syntax. For example, the condition in the line below always evaluates True because the method is_valid simply exists:

if form.is_valid:

The correct form would be

if form.is_valid():
KAZUYA NAKAJIMA
KAZUYA NAKAJIMA
8,851 Points

Very informative thread. learned a lot from this thread.