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

General question about good Python coding

Is it important to go through a full function before looping back into it?

Example: I have a dungeon game made, setup like this:

def game():
while True:  
  turns()
    show_map()
    if win == 1:
      win()
      break
    elif win == 2:
      lose()
      break
start_game() # (asks if the player wants to start a new game or quit)

That's the simple version of it.. my question is do I have to have it setup where my win() or lose() functions return, or if I can call start_game() from them (without finishing the while loop, even though starting the game again will start the loop again). I'm sure it will work if I call the start_game() before breaking the loop, but I don't know if that could cause problems with larger programs, or if it's a bad habit for Python. Make sense?

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

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,468 Points

There are times when you definitely need to have a function call itself. This recursive structure is used to continue processing data at a deeper level before returning.

In your code, there's no additional data to process when the recursion unwinds. So there is no driving need to have the function call itself.

One drawback of using this recursive approach is at each new call, an additional entry is added to the "stack". Pythons default stack limit is 1000. So after 1000 games the program will crash with a Stack Overflow.

My preference is to restructure the code to naturally fall out of the loop and have an outer function or loop start the next game.